From a137aaee37325fa85621b670930350d22ae81e34 Mon Sep 17 00:00:00 2001 From: mama-samba-braima Date: Wed, 2 Dec 2026 22:20:57 +0000 Subject: [PATCH 1/2] Add concept projects 16 to 18: batch writes, testing with a real database, virtual threads Each has a broken start/ and a fixed solution/, the demo, inspect and check launchers, and both task files. Adds them to the index and the CI list. CI now caches the Maven distribution the wrapper downloads and retries that download, so one failed fetch from Maven Central no longer fails a job. --- .github/workflows/concepts.yml | 25 + README.md | 6 +- java/concepts/README.md | 3 + java/concepts/ci-projects.json | 5 +- .../16-batch-writes/INTERVIEW_TASKS.md | 277 ++++++ .../junior-mid/16-batch-writes/README.md | 189 ++++ .../16-batch-writes/TASKS_GUIDED.md | 895 ++++++++++++++++++ .../16-batch-writes/solution/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../junior-mid/16-batch-writes/solution/check | 4 + .../16-batch-writes/solution/check.cmd | 3 + .../16-batch-writes/solution/compose.yaml | 21 + .../junior-mid/16-batch-writes/solution/demo | 4 + .../16-batch-writes/solution/demo.cmd | 3 + .../16-batch-writes/solution/inspect | 4 + .../16-batch-writes/solution/inspect.cmd | 3 + .../junior-mid/16-batch-writes/solution/mvnw | 295 ++++++ .../16-batch-writes/solution/mvnw.cmd | 189 ++++ .../16-batch-writes/solution/pom.xml | 110 +++ .../batching/ApiExceptionHandler.java | 40 + .../batching/BatchingApplication.java | 12 + .../batching/db/ManagedEntities.java | 39 + .../com/amigoscode/batching/db/Recording.java | 85 ++ .../com/amigoscode/batching/db/SqlCall.java | 29 + .../amigoscode/batching/db/SqlRecorder.java | 219 +++++ .../java/com/amigoscode/batching/demo/Db.java | 52 + .../com/amigoscode/batching/demo/Demo.java | 441 +++++++++ .../com/amigoscode/batching/demo/Feed.java | 55 ++ .../com/amigoscode/batching/demo/Inspect.java | 149 +++ .../amigoscode/batching/demo/ServerStats.java | 72 ++ .../com/amigoscode/batching/demo/Table.java | 41 + .../batching/imports/BadCsvException.java | 16 + .../batching/imports/ImportController.java | 47 + .../batching/imports/ImportService.java | 40 + .../batching/imports/ImportStrategy.java | 40 + .../batching/imports/ProductCsv.java | 184 ++++ .../batching/price/PriceChange.java | 80 ++ .../batching/price/PriceChangeRepository.java | 7 + .../batching/price/PriceHistory.java | 28 + .../batching/product/JdbcProductImporter.java | 96 ++ .../amigoscode/batching/product/Product.java | 91 ++ .../batching/product/ProductImporter.java | 88 ++ .../batching/product/ProductRepository.java | 13 + .../batching/product/ProductRow.java | 16 + .../batching/product/StockLevel.java | 55 ++ .../src/main/resources/application.properties | 28 + .../solution/src/main/resources/schema.sql | 37 + .../java/com/amigoscode/batching/Check.java | 116 +++ .../batching/ImportControllerTest.java | 95 ++ .../com/amigoscode/batching/JdbcImportIT.java | 88 ++ .../com/amigoscode/batching/OneByOneIT.java | 42 + .../batching/ParentsAndChildrenIT.java | 68 ++ .../batching/PersistenceContextIT.java | 63 ++ .../amigoscode/batching/PriceHistoryIT.java | 64 ++ .../amigoscode/batching/ProductCsvTest.java | 60 ++ .../com/amigoscode/batching/RewriteIT.java | 54 ++ .../amigoscode/batching/SequenceIdsIT.java | 68 ++ .../batching/support/DriverOptions.java | 40 + .../batching/support/IntegrationTest.java | 86 ++ .../com/amigoscode/batching/support/Rows.java | 42 + .../batching/support/ServerSide.java | 53 ++ .../src/test/resources/logback-test.xml | 11 + .../16-batch-writes/start/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../junior-mid/16-batch-writes/start/check | 4 + .../16-batch-writes/start/check.cmd | 3 + .../16-batch-writes/start/compose.yaml | 21 + .../junior-mid/16-batch-writes/start/demo | 4 + .../junior-mid/16-batch-writes/start/demo.cmd | 3 + .../junior-mid/16-batch-writes/start/inspect | 4 + .../16-batch-writes/start/inspect.cmd | 3 + .../junior-mid/16-batch-writes/start/mvnw | 295 ++++++ .../junior-mid/16-batch-writes/start/mvnw.cmd | 189 ++++ .../junior-mid/16-batch-writes/start/pom.xml | 110 +++ .../batching/ApiExceptionHandler.java | 40 + .../batching/BatchingApplication.java | 12 + .../batching/db/ManagedEntities.java | 39 + .../com/amigoscode/batching/db/Recording.java | 85 ++ .../com/amigoscode/batching/db/SqlCall.java | 29 + .../amigoscode/batching/db/SqlRecorder.java | 219 +++++ .../java/com/amigoscode/batching/demo/Db.java | 52 + .../com/amigoscode/batching/demo/Demo.java | 441 +++++++++ .../com/amigoscode/batching/demo/Feed.java | 55 ++ .../com/amigoscode/batching/demo/Inspect.java | 149 +++ .../amigoscode/batching/demo/ServerStats.java | 72 ++ .../com/amigoscode/batching/demo/Table.java | 41 + .../batching/imports/BadCsvException.java | 16 + .../batching/imports/ImportController.java | 47 + .../batching/imports/ImportService.java | 40 + .../batching/imports/ImportStrategy.java | 40 + .../batching/imports/ProductCsv.java | 184 ++++ .../batching/price/PriceChange.java | 59 ++ .../batching/price/PriceChangeRepository.java | 7 + .../batching/price/PriceHistory.java | 28 + .../batching/product/JdbcProductImporter.java | 79 ++ .../amigoscode/batching/product/Product.java | 91 ++ .../batching/product/ProductImporter.java | 78 ++ .../batching/product/ProductRepository.java | 13 + .../batching/product/ProductRow.java | 16 + .../batching/product/StockLevel.java | 54 ++ .../src/main/resources/application.properties | 21 + .../start/src/main/resources/schema.sql | 33 + .../java/com/amigoscode/batching/Check.java | 116 +++ .../batching/ImportControllerTest.java | 95 ++ .../com/amigoscode/batching/JdbcImportIT.java | 88 ++ .../com/amigoscode/batching/OneByOneIT.java | 42 + .../batching/ParentsAndChildrenIT.java | 68 ++ .../batching/PersistenceContextIT.java | 63 ++ .../amigoscode/batching/PriceHistoryIT.java | 64 ++ .../amigoscode/batching/ProductCsvTest.java | 60 ++ .../com/amigoscode/batching/RewriteIT.java | 54 ++ .../amigoscode/batching/SequenceIdsIT.java | 68 ++ .../batching/support/DriverOptions.java | 40 + .../batching/support/IntegrationTest.java | 86 ++ .../com/amigoscode/batching/support/Rows.java | 42 + .../batching/support/ServerSide.java | 53 ++ .../start/src/test/resources/logback-test.xml | 11 + .../INTERVIEW_TASKS.md | 265 ++++++ .../17-testing-with-a-real-database/README.md | 199 ++++ .../TASKS_GUIDED.md | 893 +++++++++++++++++ .../solution/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../solution/check | 4 + .../solution/check.cmd | 3 + .../solution/compose.yaml | 16 + .../solution/demo | 4 + .../solution/demo.cmd | 3 + .../solution/inspect | 4 + .../solution/inspect.cmd | 3 + .../solution/mvnw | 295 ++++++ .../solution/mvnw.cmd | 189 ++++ .../solution/pom.xml | 134 +++ .../realdb/ApiExceptionHandler.java | 23 + .../realdb/RealDatabaseApplication.java | 12 + .../com/amigoscode/realdb/catalogue/Book.java | 81 ++ .../catalogue/BookNotFoundException.java | 8 + .../realdb/catalogue/BookRepository.java | 19 + .../realdb/catalogue/CatalogueController.java | 58 ++ .../realdb/catalogue/CatalogueService.java | 41 + .../amigoscode/realdb/catalogue/Format.java | 8 + .../subscription/InvalidEmailException.java | 8 + .../realdb/subscription/Subscriber.java | 39 + .../subscription/SubscriberRepository.java | 27 + .../subscription/SubscriptionController.java | 29 + .../subscription/SubscriptionService.java | 27 + .../src/main/resources/application.properties | 13 + .../db/migration/V1__create_catalogue.sql | 20 + .../db/migration/V2__allow_audiobooks.sql | 4 + .../realdb/catalogue/BookRepositoryTest.java | 44 + .../realdb/catalogue/CatalogueApiTest.java | 66 ++ .../realdb/catalogue/ShelfTest.java | 32 + .../com/amigoscode/realdb/check/Check.java | 131 +++ .../DataJpaTestKeepsAServiceConnectionIT.java | 35 + .../DataJpaTestReplacesYourDatabaseIT.java | 38 + .../check/DataJpaTestWithReplaceNoneIT.java | 34 + .../java/com/amigoscode/realdb/check/Db.java | 47 + .../com/amigoscode/realdb/check/Demo.java | 202 ++++ .../realdb/check/H2VersusPostgresIT.java | 94 ++ .../com/amigoscode/realdb/check/Inspect.java | 138 +++ .../amigoscode/realdb/check/IsolationIT.java | 59 ++ .../realdb/check/OneContainerIT.java | 72 ++ .../com/amigoscode/realdb/check/Report.java | 100 ++ .../amigoscode/realdb/check/ShelfOrderIT.java | 39 + .../realdb/check/SubscriptionIT.java | 59 ++ .../realdb/check/TopRatedAndAudiobookIT.java | 84 ++ .../amigoscode/realdb/check/YourSuiteIT.java | 24 + .../amigoscode/realdb/check/probe/Mutant.java | 85 ++ .../probe/MutantContextCustomizerFactory.java | 39 + .../check/probe/MutantPostProcessor.java | 75 ++ .../realdb/check/probe/Recording.java | 174 ++++ .../realdb/check/probe/StudentSuite.java | 266 ++++++ .../realdb/check/probe/SuiteProbe.java | 102 ++ .../realdb/check/support/CheckPostgres.java | 37 + .../realdb/check/support/ProductionTest.java | 60 ++ .../check/support/UrlFromProperties.java | 22 + .../realdb/check/support/YourSuite.java | 84 ++ .../FakeSubscriberRepository.java | 24 + .../SubscriberRepositoryTest.java | 30 + .../subscription/SubscriptionServiceTest.java | 38 + .../realdb/support/PostgresTest.java | 47 + .../test/resources/META-INF/spring.factories | 6 + .../src/test/resources/logback-test.xml | 15 + .../start/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../start/check | 4 + .../start/check.cmd | 3 + .../start/compose.yaml | 16 + .../start/demo | 4 + .../start/demo.cmd | 3 + .../start/inspect | 4 + .../start/inspect.cmd | 3 + .../start/mvnw | 295 ++++++ .../start/mvnw.cmd | 189 ++++ .../start/pom.xml | 134 +++ .../realdb/ApiExceptionHandler.java | 23 + .../realdb/RealDatabaseApplication.java | 12 + .../com/amigoscode/realdb/catalogue/Book.java | 81 ++ .../catalogue/BookNotFoundException.java | 8 + .../realdb/catalogue/BookRepository.java | 17 + .../realdb/catalogue/CatalogueController.java | 58 ++ .../realdb/catalogue/CatalogueService.java | 41 + .../amigoscode/realdb/catalogue/Format.java | 8 + .../subscription/InvalidEmailException.java | 8 + .../realdb/subscription/Subscriber.java | 39 + .../subscription/SubscriberRepository.java | 27 + .../subscription/SubscriptionController.java | 29 + .../subscription/SubscriptionService.java | 27 + .../src/main/resources/application.properties | 13 + .../db/migration/V1__create_catalogue.sql | 20 + .../realdb/catalogue/BookRepositoryTest.java | 48 + .../realdb/catalogue/CatalogueApiTest.java | 68 ++ .../realdb/catalogue/ShelfTest.java | 29 + .../com/amigoscode/realdb/check/Check.java | 131 +++ .../DataJpaTestKeepsAServiceConnectionIT.java | 35 + .../DataJpaTestReplacesYourDatabaseIT.java | 38 + .../check/DataJpaTestWithReplaceNoneIT.java | 34 + .../java/com/amigoscode/realdb/check/Db.java | 47 + .../com/amigoscode/realdb/check/Demo.java | 202 ++++ .../realdb/check/H2VersusPostgresIT.java | 94 ++ .../com/amigoscode/realdb/check/Inspect.java | 138 +++ .../amigoscode/realdb/check/IsolationIT.java | 59 ++ .../realdb/check/OneContainerIT.java | 72 ++ .../com/amigoscode/realdb/check/Report.java | 100 ++ .../amigoscode/realdb/check/ShelfOrderIT.java | 39 + .../realdb/check/SubscriptionIT.java | 59 ++ .../realdb/check/TopRatedAndAudiobookIT.java | 84 ++ .../amigoscode/realdb/check/YourSuiteIT.java | 24 + .../amigoscode/realdb/check/probe/Mutant.java | 85 ++ .../probe/MutantContextCustomizerFactory.java | 39 + .../check/probe/MutantPostProcessor.java | 75 ++ .../realdb/check/probe/Recording.java | 174 ++++ .../realdb/check/probe/StudentSuite.java | 266 ++++++ .../realdb/check/probe/SuiteProbe.java | 102 ++ .../realdb/check/support/CheckPostgres.java | 37 + .../realdb/check/support/ProductionTest.java | 60 ++ .../check/support/UrlFromProperties.java | 22 + .../realdb/check/support/YourSuite.java | 84 ++ .../FakeSubscriberRepository.java | 24 + .../subscription/SubscriptionServiceTest.java | 35 + .../test/resources/META-INF/spring.factories | 6 + .../start/src/test/resources/logback-test.xml | 15 + .../18-virtual-threads/INTERVIEW_TASKS.md | 271 ++++++ .../junior-mid/18-virtual-threads/README.md | 205 ++++ .../18-virtual-threads/TASKS_GUIDED.md | 797 ++++++++++++++++ .../solution/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../18-virtual-threads/solution/check | 4 + .../18-virtual-threads/solution/check.cmd | 3 + .../18-virtual-threads/solution/compose.yaml | 16 + .../18-virtual-threads/solution/demo | 4 + .../18-virtual-threads/solution/demo.cmd | 3 + .../18-virtual-threads/solution/inspect | 4 + .../18-virtual-threads/solution/inspect.cmd | 3 + .../18-virtual-threads/solution/mvnw | 295 ++++++ .../18-virtual-threads/solution/mvnw.cmd | 189 ++++ .../18-virtual-threads/solution/pom.xml | 105 ++ .../virtualthreads/ApiExceptionHandler.java | 68 ++ .../VirtualThreadsApplication.java | 12 + .../airline/AirlineBusyException.java | 9 + .../virtualthreads/airline/AirlineClient.java | 10 + .../virtualthreads/airline/AirlineQuote.java | 5 + .../airline/AirlineUnavailableException.java | 13 + .../virtualthreads/airline/FakeAirline.java | 129 +++ .../airline/HttpAirlineClient.java | 65 ++ .../virtualthreads/cpu/CpuController.java | 48 + .../amigoscode/virtualthreads/demo/Db.java | 41 + .../amigoscode/virtualthreads/demo/Demo.java | 415 ++++++++ .../virtualthreads/demo/Inspect.java | 254 +++++ .../amigoscode/virtualthreads/demo/Tool.java | 200 ++++ .../exhibit/PooledFareController.java | 70 ++ .../virtualthreads/fares/FareController.java | 35 + .../virtualthreads/fares/FareQuote.java | 10 + .../virtualthreads/fares/FareService.java | 70 ++ .../virtualthreads/fares/Route.java | 4 + .../virtualthreads/fares/RouteRepository.java | 27 + .../fares/SearchRepository.java | 22 + .../fares/UnknownRouteException.java | 8 + .../virtualthreads/money/ExchangeRates.java | 21 + .../virtualthreads/money/RateTable.java | 73 ++ .../money/UnknownCurrencyException.java | 8 + .../virtualthreads/pinning/PinningLab.java | 194 ++++ .../threads/InFlightRequests.java | 107 +++ .../virtualthreads/threads/ServerThreads.java | 55 ++ .../src/main/resources/application.properties | 29 + .../solution/src/main/resources/schema.sql | 27 + .../virtualthreads/AirlineLimitIT.java | 85 ++ .../virtualthreads/CarrierThreadsTest.java | 74 ++ .../com/amigoscode/virtualthreads/Check.java | 119 +++ .../virtualthreads/ConnectionPoolIT.java | 69 ++ .../virtualthreads/ExchangeRatesTest.java | 35 + .../virtualthreads/FareControllerTest.java | 98 ++ .../virtualthreads/PinningTest.java | 182 ++++ .../virtualthreads/PlatformThreadsIT.java | 56 ++ .../RateTableOnPlatformThreadsIT.java | 27 + .../RateTableOnVirtualThreadsIT.java | 32 + .../virtualthreads/VirtualThreadsIT.java | 72 ++ .../support/ControllableAirline.java | 122 +++ .../support/IntegrationTest.java | 103 ++ .../support/OnPlatformThreads.java | 14 + .../support/OnVirtualThreads.java | 15 + .../virtualthreads/support/Searches.java | 101 ++ .../src/test/resources/logback-test.xml | 13 + .../18-virtual-threads/start/.mvn/jvm.config | 2 + .../.mvn/wrapper/maven-wrapper.properties | 3 + .../junior-mid/18-virtual-threads/start/check | 4 + .../18-virtual-threads/start/check.cmd | 3 + .../18-virtual-threads/start/compose.yaml | 16 + .../junior-mid/18-virtual-threads/start/demo | 4 + .../18-virtual-threads/start/demo.cmd | 3 + .../18-virtual-threads/start/inspect | 4 + .../18-virtual-threads/start/inspect.cmd | 3 + .../junior-mid/18-virtual-threads/start/mvnw | 295 ++++++ .../18-virtual-threads/start/mvnw.cmd | 189 ++++ .../18-virtual-threads/start/pom.xml | 105 ++ .../virtualthreads/ApiExceptionHandler.java | 68 ++ .../VirtualThreadsApplication.java | 12 + .../airline/AirlineBusyException.java | 9 + .../virtualthreads/airline/AirlineClient.java | 10 + .../virtualthreads/airline/AirlineQuote.java | 5 + .../airline/AirlineUnavailableException.java | 13 + .../virtualthreads/airline/FakeAirline.java | 129 +++ .../airline/HttpAirlineClient.java | 65 ++ .../virtualthreads/cpu/CpuController.java | 48 + .../amigoscode/virtualthreads/demo/Db.java | 41 + .../amigoscode/virtualthreads/demo/Demo.java | 415 ++++++++ .../virtualthreads/demo/Inspect.java | 254 +++++ .../amigoscode/virtualthreads/demo/Tool.java | 200 ++++ .../exhibit/PooledFareController.java | 70 ++ .../virtualthreads/fares/FareController.java | 35 + .../virtualthreads/fares/FareQuote.java | 10 + .../virtualthreads/fares/FareService.java | 59 ++ .../virtualthreads/fares/Route.java | 4 + .../virtualthreads/fares/RouteRepository.java | 27 + .../fares/SearchRepository.java | 22 + .../fares/UnknownRouteException.java | 8 + .../virtualthreads/money/ExchangeRates.java | 21 + .../virtualthreads/money/RateTable.java | 73 ++ .../money/UnknownCurrencyException.java | 8 + .../virtualthreads/pinning/PinningLab.java | 194 ++++ .../threads/InFlightRequests.java | 107 +++ .../virtualthreads/threads/ServerThreads.java | 55 ++ .../src/main/resources/application.properties | 29 + .../start/src/main/resources/schema.sql | 27 + .../virtualthreads/AirlineLimitIT.java | 85 ++ .../virtualthreads/CarrierThreadsTest.java | 74 ++ .../com/amigoscode/virtualthreads/Check.java | 119 +++ .../virtualthreads/ConnectionPoolIT.java | 69 ++ .../virtualthreads/ExchangeRatesTest.java | 35 + .../virtualthreads/FareControllerTest.java | 98 ++ .../virtualthreads/PinningTest.java | 182 ++++ .../virtualthreads/PlatformThreadsIT.java | 56 ++ .../RateTableOnPlatformThreadsIT.java | 27 + .../RateTableOnVirtualThreadsIT.java | 32 + .../virtualthreads/VirtualThreadsIT.java | 72 ++ .../support/ControllableAirline.java | 122 +++ .../support/IntegrationTest.java | 103 ++ .../support/OnPlatformThreads.java | 14 + .../support/OnVirtualThreads.java | 15 + .../virtualthreads/support/Searches.java | 101 ++ .../start/src/test/resources/logback-test.xml | 13 + 360 files changed, 25966 insertions(+), 4 deletions(-) create mode 100644 java/concepts/junior-mid/16-batch-writes/INTERVIEW_TASKS.md create mode 100644 java/concepts/junior-mid/16-batch-writes/README.md create mode 100644 java/concepts/junior-mid/16-batch-writes/TASKS_GUIDED.md create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/16-batch-writes/solution/check create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/check.cmd create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/compose.yaml create mode 100755 java/concepts/junior-mid/16-batch-writes/solution/demo create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/demo.cmd create mode 100755 java/concepts/junior-mid/16-batch-writes/solution/inspect create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/inspect.cmd create mode 100755 java/concepts/junior-mid/16-batch-writes/solution/mvnw create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/mvnw.cmd create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/pom.xml create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java create mode 100644 java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml create mode 100644 java/concepts/junior-mid/16-batch-writes/start/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/16-batch-writes/start/check create mode 100644 java/concepts/junior-mid/16-batch-writes/start/check.cmd create mode 100644 java/concepts/junior-mid/16-batch-writes/start/compose.yaml create mode 100755 java/concepts/junior-mid/16-batch-writes/start/demo create mode 100644 java/concepts/junior-mid/16-batch-writes/start/demo.cmd create mode 100755 java/concepts/junior-mid/16-batch-writes/start/inspect create mode 100644 java/concepts/junior-mid/16-batch-writes/start/inspect.cmd create mode 100755 java/concepts/junior-mid/16-batch-writes/start/mvnw create mode 100644 java/concepts/junior-mid/16-batch-writes/start/mvnw.cmd create mode 100644 java/concepts/junior-mid/16-batch-writes/start/pom.xml create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java create mode 100644 java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/README.md create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/solution/check create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw.cmd create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Check.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Db.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Demo.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Inspect.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/IsolationIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Report.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Recording.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/support/PostgresTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/META-INF/spring.factories create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/logback-test.xml create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/start/check create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/check.cmd create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/compose.yaml create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/start/demo create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/demo.cmd create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect.cmd create mode 100755 java/concepts/junior-mid/17-testing-with-a-real-database/start/mvnw create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/mvnw.cmd create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/pom.xml create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Book.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Format.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/db/migration/V1__create_catalogue.sql create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Check.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Db.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Demo.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Inspect.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/IsolationIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Report.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Recording.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/META-INF/spring.factories create mode 100644 java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/logback-test.xml create mode 100644 java/concepts/junior-mid/18-virtual-threads/INTERVIEW_TASKS.md create mode 100644 java/concepts/junior-mid/18-virtual-threads/README.md create mode 100644 java/concepts/junior-mid/18-virtual-threads/TASKS_GUIDED.md create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/18-virtual-threads/solution/check create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/check.cmd create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/compose.yaml create mode 100755 java/concepts/junior-mid/18-virtual-threads/solution/demo create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/demo.cmd create mode 100755 java/concepts/junior-mid/18-virtual-threads/solution/inspect create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/inspect.cmd create mode 100755 java/concepts/junior-mid/18-virtual-threads/solution/mvnw create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/mvnw.cmd create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/pom.xml create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Db.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/Route.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/schema.sql create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/Check.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PinningTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/Searches.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/solution/src/test/resources/logback-test.xml create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/.mvn/jvm.config create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/.mvn/wrapper/maven-wrapper.properties create mode 100755 java/concepts/junior-mid/18-virtual-threads/start/check create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/check.cmd create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/compose.yaml create mode 100755 java/concepts/junior-mid/18-virtual-threads/start/demo create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/demo.cmd create mode 100755 java/concepts/junior-mid/18-virtual-threads/start/inspect create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/inspect.cmd create mode 100755 java/concepts/junior-mid/18-virtual-threads/start/mvnw create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/mvnw.cmd create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/pom.xml create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Db.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/Route.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/application.properties create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/schema.sql create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/Check.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PinningTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/Searches.java create mode 100644 java/concepts/junior-mid/18-virtual-threads/start/src/test/resources/logback-test.xml diff --git a/.github/workflows/concepts.yml b/.github/workflows/concepts.yml index 89356e8..bc054d4 100644 --- a/.github/workflows/concepts.yml +++ b/.github/workflows/concepts.yml @@ -51,6 +51,18 @@ jobs: distribution: temurin java-version: "25" cache: maven + # setup-java caches ~/.m2/repository only. The Maven that ./mvnw downloads lives in + # ~/.m2/wrapper, so cache that too, and fetch it with retries: a single failed download + # from Maven Central would otherwise fail the whole job before any test runs. + - uses: actions/cache@v4 + with: + path: ~/.m2/wrapper + key: maven-wrapper-${{ runner.os }}-${{ hashFiles('java/concepts/**/.mvn/wrapper/maven-wrapper.properties') }} + - name: Download Maven (with retries) + run: | + cd "${{ matrix.project.path }}/solution" + for i in 1 2 3 4 5; do ./mvnw -q -v && exit 0; echo "attempt $i failed, retrying"; sleep $((i * 10)); done + exit 1 # start/ must fail with the documented count; solution/ must pass everything. - name: Verify start/ and solution/ run: > @@ -70,6 +82,19 @@ jobs: distribution: temurin java-version: "25" cache: maven + - uses: actions/cache@v4 + with: + path: ~/.m2/wrapper + key: maven-wrapper-${{ runner.os }}-${{ hashFiles('java/concepts/**/.mvn/wrapper/maven-wrapper.properties') }} + - name: Download Maven (with retries) + shell: pwsh + run: | + for ($i = 1; $i -le 5; $i++) { + & java/concepts/junior-mid/06-thread-safety/solution/mvnw.cmd -q -v + if ($LASTEXITCODE -eq 0) { exit 0 } + Write-Host "attempt $i failed, retrying"; Start-Sleep -Seconds ($i * 10) + } + exit 1 # Hosted Windows runners cannot run the Postgres containers, so this checks what it can: # every project's demo.cmd compiles the project and passes its arguments through. - name: demo.cmd --help in every project diff --git a/README.md b/README.md index 82dbb7d..74b283c 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 fifteen so far, numbered in the suggested order from -> `01-transactional` to `15-equals-and-hashcode`: see the [list](java/concepts/README.md). +> `solution/` folders side by side. There are eighteen so far, numbered in the suggested order from +> `01-transactional` to `18-virtual-threads`: see the [list](java/concepts/README.md). ## Structure @@ -97,7 +97,7 @@ interview-prep/ │ ├── karat-drills/ │ ├── secret-storage/ │ ├── concepts/ -│ │ └── junior-mid/ (01-transactional ... 15-equals-and-hashcode) +│ │ └── junior-mid/ (01-transactional ... 18-virtual-threads) │ ├── DELIVERY_HERO.md │ └── KARAT.md ├── python/ diff --git a/java/concepts/README.md b/java/concepts/README.md index eefafd6..378b6e5 100644 --- a/java/concepts/README.md +++ b/java/concepts/README.md @@ -26,6 +26,9 @@ under [`java/`](../). | 13 | Junior / mid | [Money as double](junior-mid/13-money-as-double/) | 1,000 payments of 0.10 add up to 100.00 and 99.99 is paid out | | 14 | Junior / mid | [Authorisation and JWT](junior-mid/14-authorisation-and-jwt/) | Merchant A reads merchant B's invoices by changing the id in the URL | | 15 | Junior / mid | [equals and hashCode](junior-mid/15-equals-and-hashcode/) | An item goes into a set, its quantity changes, and the set can no longer find it | +| 16 | Junior / mid | [Batch writes](junior-mid/16-batch-writes/) | Importing 10,000 rows takes 10,000 round trips to the database | +| 17 | Junior / mid | [Testing with a real database](junior-mid/17-testing-with-a-real-database/) | Every test is green and 4 of 4 features are broken on Postgres | +| 18 | Junior / mid | [Virtual threads](junior-mid/18-virtual-threads/) | 200 slow requests, at most 20 in flight; the rest wait in a queue | 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 9f80ccc..e6433a7 100644 --- a/java/concepts/ci-projects.json +++ b/java/concepts/ci-projects.json @@ -13,5 +13,8 @@ { "path": "java/concepts/junior-mid/12-caching-with-redis", "startPass": 13, "total": 28 }, { "path": "java/concepts/junior-mid/13-money-as-double", "startPass": 9, "total": 34 }, { "path": "java/concepts/junior-mid/14-authorisation-and-jwt", "startPass": 15, "total": 31 }, - { "path": "java/concepts/junior-mid/15-equals-and-hashcode", "startPass": 14, "total": 34 } + { "path": "java/concepts/junior-mid/15-equals-and-hashcode", "startPass": 14, "total": 34 }, + { "path": "java/concepts/junior-mid/16-batch-writes", "startPass": 17, "total": 32 }, + { "path": "java/concepts/junior-mid/17-testing-with-a-real-database", "startPass": 9, "total": 24 }, + { "path": "java/concepts/junior-mid/18-virtual-threads", "startPass": 17, "total": 25 } ] diff --git a/java/concepts/junior-mid/16-batch-writes/INTERVIEW_TASKS.md b/java/concepts/junior-mid/16-batch-writes/INTERVIEW_TASKS.md new file mode 100644 index 0000000..11a86ef --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/INTERVIEW_TASKS.md @@ -0,0 +1,277 @@ +# Interview Tasks — Batch Writes + +> **In `start/`, `./check` FAILS on purpose: 17 of 32 checks pass.** Tasks 2, 4, 5, 6, 7 and 8 turn +> the other 15 green. Tasks 1 and 3 are about looking: you run things and answer questions. + +Do the tasks in order: each fix builds on the one before. After every change, run `./demo` and +`./inspect` before you move on: a green test tells you the fix works, the numbers tell 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 +`ProductImporter.importOneByOne`: it stays as it is so you can compare against it. Keep +`hibernate.jdbc.batch_size=50`: the tests count batches of 50. + +--- + +## Task 1: See 10,000 Round Trips (10 min) + +**Story:** *The nightly import of the supplier's feed has gone from seconds to minutes since the feed +grew to 10,000 products. A colleague says "but we turned batching on", and points at +`hibernate.jdbc.batch_size=50`. Before you change anything, find out what the import really sends.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. How many round trips did 10,000 rows take? How many rows did + each one carry? How many statements did Postgres execute? +2. Open `application.properties`. Is batching configured? Then why is nothing batched? +3. `./demo --sql`. What is the kind of each round trip, and how many rows does it carry? +4. `./demo --strategy one-by-one`. Compare round trips, commits and time with step 1. +5. Read the last line of "Peak entities held". What is in memory at the end of the import? + +**Acceptance Criteria** (`./check 1`, already passing: these tests document the problem) +- [ ] You can say how many round trips 10,000 rows took, and why that is slow even on a fast database +- [ ] You can say what `RETURNING *` at the end of the INSERT tells you +- [ ] You can explain what one transaction per row adds on top +- [ ] `OneByOneIT.everyRowIsItsOwnRoundTripAndTransaction` and `OneByOneIT.aBadRowLeavesHalfAnImport` pass + +**Hints:** +- Look at the "Product ids:" line the demo prints at the top +- Something about the id makes Hibernate send each INSERT at once, instead of holding it for a batch + +--- + +## Task 2: Let Hibernate Batch: SEQUENCE Instead of IDENTITY (20 min) + +**Story:** *Make the import send its INSERTs in batches of 50. The ids must still come from the +database, and anything else that inserts into `product` must never get an id the import also uses. +Fix `Product` and `schema.sql`.* + +**Acceptance Criteria** (`./check 2`) +- [ ] 2,000 products are sent as 40 INSERT batches of 50 + — `SequenceIdsIT.insertsAreSentInBatches` +- [ ] The ids come from a sequence, 50 at a time: at most 41 `nextval` calls for 2,000 products + — `SequenceIdsIT.idsComeFromTheSequenceFiftyAtATime` +- [ ] `Product` uses a SEQUENCE generator whose `allocationSize` equals the sequence's `INCREMENT BY` + — `SequenceIdsIT.allocationSizeMatchesTheSequence` +- [ ] Two imports with a plain SQL INSERT in between never hand out the same id twice + — `SequenceIdsIT.idsNeverClash` (already passing: keep it that way) +- [ ] `./demo` no longer prints `RESULT: 10,000 ROUND TRIPS` + +**Hints:** +- `@GeneratedValue(strategy = GenerationType.SEQUENCE)` and `@SequenceGenerator` +- `schema.sql` runs on every start, so you can change the table and create the sequence there +- Try `allocationSize = 1` first and run `./demo`. Count the `nextval` calls. Then make the sequence + and `allocationSize` agree on a bigger number. What happens if they do not agree? + +--- + +## Task 3: Inspect the Batches and the Sequence (15 min) + +**Story:** *The import is fast now. Before you tell the team, make sure you can explain every number +it prints.* + +**Steps:** +1. `./demo --sql`. Why are the first 25 round trips all `nextval`? When are the INSERTs sent? +2. `./demo`, then `./inspect`. How many times was `nextval` called for 10,000 rows? Why that number + and not exactly 200? What is the sequence's last value, and what is the highest product id? +3. Still in `./inspect`: where does `stock_level` get its ids from? Which sequence belongs to it? +4. Compare "What the application sent" with "What Postgres executed" in `./demo`. How many round + trips carried INSERTs? How many INSERT statements did Postgres execute? +5. No command for this one: if the application stops after using 10 of its block of 50 ids, what + happens to the other 40? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can explain what `allocationSize` does and why it must equal `INCREMENT BY` +- [ ] You can say why a plain `INSERT` using the column default cannot clash with ids Hibernate hands out +- [ ] You can say what a JDBC batch saves, and what it does not save on the server +- [ ] You can explain where gaps in the ids come from, and why they do not matter + +--- + +## Task 4: Multi-Row INSERTs: `reWriteBatchedInserts` (10 min) + +**Story:** *A JDBC batch saves round trips, but Postgres still runs 10,000 separate INSERTs. Make +the driver send fewer, bigger statements. No Java changes.* + +**Acceptance Criteria** (`./check 4`) +- [ ] The connections of the pool have `reWriteBatchedInserts` switched on + — `RewriteIT.theDriverRewritesBatches` +- [ ] 2,000 products arrive as multi-row INSERTs: at most 200 INSERT executions in Postgres + — `RewriteIT.postgresExecutesMultiRowInserts` +- [ ] Every row still arrives exactly once — `RewriteIT.everyRowArrivesOnce` (already passing) +- [ ] You can say how many statements Postgres executed for one batch of 50, and what sizes they had + +**Hints:** +- It is an option of the Postgres JDBC driver. Options go on the JDBC URL after a `?` +- `./demo --strategy rewrite` shows the effect before you change anything. `./demo --rewrite off` + turns it off again for one run, so you can compare +- Does the driver rewrite UPDATEs too? Check in Task 5 + +--- + +## Task 5: Parents and Children: `order_inserts` and `order_updates` (20 min) + +**Story:** *The feed now carries stock for three warehouses, and every product is saved together with +its 3 stock levels (`./demo --stock`). The next day the same feed comes back with new prices and new +stock. Both the import and the update are slow again. Fix `StockLevel` and `application.properties`.* + +**Acceptance Criteria** (`./check 5`) +- [ ] 500 products and 1,500 stock levels go in full batches: at most 10 product and 30 stock level + batches — `ParentsAndChildrenIT.insertsAreSortedIntoFullBatches` +- [ ] Stock levels get their ids from a sequence too + — `ParentsAndChildrenIT.stockLevelIdsComeFromASequence` +- [ ] A new price and new stock for 500 products takes at most 40 UPDATE round trips + — `ParentsAndChildrenIT.updatesAreSortedIntoFullBatches` +- [ ] Every stock level is stored and points to its own product + — `ParentsAndChildrenIT.everyStockLevelBelongsToItsProduct` (already passing) + +**Hints:** +- Run `./demo --stock` before you change anything. Look at the product batches. Why are they 1 row + each, when Task 2 fixed `Product`? +- Fix the ids first, then run `./demo --stock --sql --rows 100` and read the order of the statements +- A JDBC batch is "the same statement, many times". What ends a batch? +- Two Hibernate properties sort the statements of a flush by table + +--- + +## Task 6: Flat Memory: Flush and Clear (20 min) + +**Story:** *Next month the feed will have 1,000,000 rows. `./demo --rows 100000` shows the import +holding every product in memory until the end. Keep memory flat, whatever the size of the file, and +keep the import in one transaction: a feed is imported completely or not at all. Fix +`ProductImporter.importBatched`.* + +**Acceptance Criteria** (`./check 6`) +- [ ] Importing 2,000 products never holds more than 50 entities in the persistence context + — `PersistenceContextIT.productsAreNotKeptInMemory` +- [ ] With stock levels, never more than 200 (50 products and their 150 stock levels) + — `PersistenceContextIT.productsWithStockAreNotKeptInMemory` +- [ ] The batches stay full: still 40 INSERT batches of 50 for 2,000 products + — `PersistenceContextIT.clearingKeepsTheBatchesFull` +- [ ] A bad row near the end still rolls back the whole import + — `PersistenceContextIT.flushIsNotCommit` (already passing: keep it that way) +- [ ] `./demo` prints `RESULT: OK` + +**Hints:** +- The rows arrive one at a time (`Iterable`). Do you need all of them in a list? +- `EntityManager.flush()` sends what is pending. `EntityManager.clear()` makes Hibernate forget every + entity it manages. In which order, and how often? +- How many rows should you clear after, if batches are 50 rows? + +--- + +## Task 7: Ids Made in Java: No SELECT Before Every INSERT (15 min) + +**Story:** *Every import also writes a price history. Its ids are UUIDs made in Java, "so we never +wait for the database". `./demo --prices` shows 10,000 SELECTs nobody wrote. Fix `PriceChange`.* + +**Acceptance Criteria** (`./check 7`) +- [ ] Saving 1,000 price changes sends no SELECT, only 20 INSERT batches + — `PriceHistoryIT.noSelectBeforeEveryInsert` +- [ ] `saveAll()` returns the objects you gave it, not copies of them + — `PriceHistoryIT.saveAllPersistsTheSameObjects` +- [ ] A price change loaded from the database and saved again is updated, not inserted a second time + — `PriceHistoryIT.aLoadedPriceChangeIsUpdated` (already passing: keep it that way) + +**Hints:** +- Read `SimpleJpaRepository.save` in your IDE. It does one of two things. How does it choose? +- What does "new" mean to Spring Data when the entity has no `@Version`? +- Spring Data has an interface that lets the entity answer that question itself +- After a price change has been saved or loaded, it is not new any more. JPA has callbacks for both + +--- + +## Task 8: Leave JPA: JdbcTemplate and COPY, Then Compare (25 min) + +**Story:** *For the 1,000,000-row feed, the team asks whether JPA is the right tool at all. Make the +two non-JPA importers in `JdbcProductImporter` correct and fast, then compare all five strategies.* + +**Acceptance Criteria** (`./check 8`) +- [ ] `JdbcTemplate`: 2,000 products in 40 round trips, batches of 50 + — `JdbcImportIT.jdbcTemplateSendsBatches` +- [ ] `JdbcTemplate`: an awkward name is stored exactly as sent — `JdbcImportIT.jdbcTemplateStoresAwkwardNames` + (already passing) +- [ ] COPY: 2,000 products in one statement — `JdbcImportIT.copyIsOneStatement` (already passing) +- [ ] COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent + — `JdbcImportIT.copyStoresAwkwardNames` +- [ ] COPY: one bad row and nothing is stored — `JdbcImportIT.oneBadRowStopsTheWholeCopy` (already passing) +- [ ] `./check` prints 32 of 32 + +**Then compare.** Run each and note round trips, statements Postgres executed, commits and time: +- `./demo --strategy one-by-one` +- `./demo --rewrite off` +- `./demo` +- `./demo --strategy jdbc` +- `./demo --strategy copy` +- The last four again with `--rows 100000` + +**Hints:** +- `JdbcTemplate.batchUpdate(sql, rows, batchSize, setter)` +- `COPY ... WITH (FORMAT csv)`: a field in double quotes may hold commas and line breaks; a double + quote inside it is written twice +- What does `--stock` do with `--strategy jdbc`? Why? + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- You set `hibernate.jdbc.batch_size` and nothing changed. Why? (The entity uses + `GenerationType.IDENTITY`. The id only exists after Postgres has run the INSERT, and Hibernate needs + it at `persist` time to keep the entity in the persistence context, so it runs every INSERT on its + own, immediately. Insert batching is silently off. Use a sequence.) +- What is `allocationSize`, and what goes wrong if it does not match the sequence? (How many ids + Hibernate takes from one `nextval`. With the pooled optimizer, one `nextval` per 50 rows instead of + one per row. It must equal the sequence's `INCREMENT BY`: Hibernate 7 refuses to start when it does + not, because the blocks it hands out would overlap the values the sequence gives everyone else.) +- Is it safe when another program inserts into the same table with `nextval`? (Yes with the pooled + optimizer: the value from the sequence is the top of the block Hibernate uses, so a value someone + else takes is never inside a block Hibernate is using.) +- Where do gaps in the ids come from, and do they matter? (Blocks of ids that were allocated and not + used before the application stopped, and sequences that never roll back. They do not matter: an id + identifies a row, it does not count rows.) +- What does a JDBC batch save, and what does `reWriteBatchedInserts` add? (A batch sends many + statements in one round trip; Postgres still executes each one on its own. The driver option rewrites + the batch into a few multi-row INSERTs, so the server executes far fewer statements. INSERTs only.) +- Why do parents and children break batching, and how do you fix it? (A batch is one statement run + many times. Cascading saves alternate parent, children, parent, children, and every switch ends the + batch. `hibernate.order_inserts` and `order_updates` sort the statements of a flush by table.) +- What is the difference between `flush()` and commit? (Flush sends the pending SQL inside the current + transaction. Commit ends the transaction and makes it permanent. You can flush a hundred times and + still roll back everything.) +- How do you import a million rows with JPA without running out of memory? (One transaction, flush + and clear every `batch_size` rows so the persistence context never holds more than one batch. Or a + `StatelessSession`, which has no persistence context at all, but no cascades, no dirty checking, and + on Hibernate 7.2 it does not even batch until you call `setJdbcBatchSize`.) +- Why does `saveAll` run a SELECT before every INSERT? (Spring Data calls `persist` for a new entity + and `merge` otherwise. Without `@Version`, new means "the id is null". An id assigned in Java is never + null, so it merges, and merge must SELECT to know whether the row exists. Fix with `Persistable`, a + `@Version` field, or let Hibernate generate the id.) +- When would you leave JPA for a bulk load? (When you do not need entities: no cascades, no callbacks, + no optimistic locking, just rows. `JdbcTemplate.batchUpdate` for big imports, `COPY` for bulk loads. + The price: you write the SQL or the CSV yourself, ids come from column defaults, and one bad row + fails the whole COPY.) +- One bad row in 1,000,000. What do you want to happen? (A product decision, not a technical detail. + All or nothing: one transaction, as here. Or load what you can: validate rows before writing, commit + in chunks and record how far you got, or COPY into a staging table without constraints and move the + good rows with one `INSERT ... SELECT`.) + +## Tips for Interviewers + +- The most common wrong answer is "set `hibernate.jdbc.batch_size`". Ask the candidate to predict + the round trips of `./demo` before running it. A strong candidate asks how the ids are generated. +- Ask what `RETURNING *` at the end of the IDENTITY INSERT means. It is the driver fetching the + generated id: the reason the INSERT cannot wait for a batch. +- In Task 2, watch for `allocationSize = 1`. It batches the INSERTs and adds a SELECT per row: 10,200 + round trips. Ask them to count the `nextval` calls. +- In Task 6, ask "is it still one transaction?". Candidates who commit every 50 rows have changed what + a failed import leaves behind, and should say so. +- In Task 7, a `Persistable` whose `isNew()` always returns true passes the first two tests and then + inserts a loaded entity a second time (duplicate key). Ask what `@PostLoad` is for. +- For senior candidates, the last question is the real one: what happens to row 600,001 of a feed, and + who decides. diff --git a/java/concepts/junior-mid/16-batch-writes/README.md b/java/concepts/junior-mid/16-batch-writes/README.md new file mode 100644 index 0000000..bf5d7ab --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/README.md @@ -0,0 +1,189 @@ +# Batch Writes — JDBC Batching with Spring Boot and JPA + +> **In `start/`, `./check` FAILS on purpose: 17 of 32 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5, 6, 7 and 8 turn the other 15 green. + +A shop imports its supplier's product feed every night: 10,000 rows of CSV. The import makes +**10,000 round trips** to Postgres, one INSERT at a time, although `application.properties` clearly +says `hibernate.jdbc.batch_size=50`. And it keeps all 10,000 products in memory until the very end. +Nothing crashes, so nobody notices until the feed grows. This project lets you count the round trips, +then fix them one cause at a time and see what Hibernate, the JDBC driver and Postgres each do +differently. + +It answers the interview questions students most often get wrong: + +- "You set `hibernate.jdbc.batch_size` and nothing changed. Why?" +- "IDENTITY or SEQUENCE? What is `allocationSize`?" +- "How do you insert a million rows with Spring Data JPA?" +- "Why does `saveAll` run a SELECT before every INSERT?" +- "What is the difference between `flush()` and commit?" +- "When would you not use JPA for a bulk load?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate 7), JdbcTemplate +- **PostgreSQL 17** in Docker, with `pg_stat_statements` +- 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 5455 +./demo # 10,000 rows, 10,000 round trips +./check # 17 of 32 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` — count the round trips of one import + +Starts the real application, sends it a generated CSV feed over HTTP, and prints what the +application sent (counted at the JDBC driver: one `execute` or one `executeBatch` is one round trip), +what Postgres executed (counted by the server with `pg_stat_statements`), how many entities Hibernate +held in memory, and the time it took. Ends with one or more `RESULT` lines. Every run starts from +empty tables. + +``` +./demo 10,000 products, the JPA import (strategy batched) +./demo --rows 100000 a bigger feed +./demo --strategy one-by-one one-by-one | batched | rewrite | jdbc | copy +./demo --rewrite on force the driver's reWriteBatchedInserts on (or off) for this run +./demo --stock every product gets 3 stock levels, then a second feed updates them +./demo --prices write the price history instead: ids are UUIDs made in Java +./demo --sql also list the first 25 round trips, in order +./demo --help +``` + +The time is there for colour only. It changes from run to run; the counts do not. + +### `./inspect` — look inside the database + +Run it after `./demo`. It shows where each table gets its ids (identity, sequence default, or the +application), the sequences and how far they have moved, how far apart the stored ids are, and every +statement Postgres executed for the last request of the 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. They never measure time: they count round trips, statements, +rows and entities. **Never edit, delete or disable a test.** + +## The code + +``` +start/src/main/ +├── resources/ +│ ├── schema.sql the tables, and where their ids come from. Tasks 2 and 5 +│ └── application.properties the batch size and the driver options. Tasks 4 and 5 +└── java/com/amigoscode/batching/ + ├── product/ + │ ├── Product.java the entity. Task 2 + │ ├── StockLevel.java a product's stock in one warehouse. Task 5 + │ ├── ProductImporter.java the JPA import: one-by-one, batched, and the update. Task 6 + │ └── JdbcProductImporter.java JdbcTemplate.batchUpdate and COPY. Task 8 + ├── price/ + │ ├── PriceChange.java one line of the price history, its id made in Java. Task 7 + │ └── PriceHistory.java saves the price changes with saveAll + ├── imports/ the endpoints and the CSV reader + ├── db/ SqlRecorder and ManagedEntities: what the demo and tests count. Nothing to change here + └── demo/ the demo and inspect tools. Nothing to change here +``` + +| Endpoint | Body | What it does | +|---|---|---| +| `POST /api/imports/products?strategy=batched` | CSV: `sku,name,price` and optional warehouse columns | Imports new products: `one-by-one`, `batched`, `jdbc` or `copy` | +| `PUT /api/imports/products` | The same CSV | The next day's feed: a new price and new stock for every product | +| `POST /api/imports/prices` | The same CSV | One price change per row, into the price history | + +`ProductImporter.importOneByOne` stays as it is for ever, so you can always compare against it. + +## 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. Do them in order: each fix builds on the one before. + +| Task | What you do | Checked by | +|---|---|---| +| 1 | See 10,000 round trips | `./check 1` (passes: it documents the problem) | +| 2 | Let Hibernate batch: SEQUENCE instead of IDENTITY | `./check 2` | +| 3 | Inspect the batches and the sequence | you answer questions | +| 4 | Multi-row INSERTs: `reWriteBatchedInserts` | `./check 4` | +| 5 | Parents and children: `order_inserts` and `order_updates` | `./check 5` | +| 6 | Flat memory: flush and clear | `./check 6` | +| 7 | Ids made in Java: no SELECT before every INSERT | `./check 7` | +| 8 | Leave JPA: JdbcTemplate and COPY, then compare everything | `./check 8` | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 32 of 32. + +`start/` and `solution/` use the same database. Every start drops the tables and creates them again +from `schema.sql`, so switching between them is safe. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +
+Spoiler: the causes and the fixes + +**IDENTITY (Task 2).** With `GenerationType.IDENTITY` the id only exists once Postgres has run the +INSERT, and Hibernate needs the id the moment you call `persist`. So it sends every INSERT on its +own, straight away, and `hibernate.jdbc.batch_size` does nothing for inserts. Fix: a sequence with +`INCREMENT BY 50` and `@SequenceGenerator(allocationSize = 50)`. Hibernate's pooled optimizer asks +the sequence once per 50 ids (201 `nextval` calls for 10,000 rows) and can batch the INSERTs: 401 +round trips instead of 10,000. `allocationSize` must equal `INCREMENT BY`, or Hibernate 7 refuses to +start. + +**Multi-row INSERTs (Task 4).** A JDBC batch saves round trips, but Postgres still executes one INSERT +per row. `reWriteBatchedInserts=true` on the JDBC URL makes the driver rewrite a batch of 50 into +multi-row `INSERT ... VALUES (...), (...)` statements (here 32 + 16 + 2 rows): 600 statements instead +of 10,000. INSERTs only, not UPDATEs. + +**Parents and children (Task 5).** One IDENTITY child is enough to break the parent's batches too. With +both on sequences, the INSERTs still alternate: product, 3 stock levels, product... and every change +of statement ends the batch. `hibernate.order_inserts=true` and `order_updates=true` sort the +statements of a flush by table: 1,602 round trips instead of 20,802. + +**Memory (Task 6).** Every entity you persist stays in the persistence context, with a snapshot for +dirty checking, until the transaction ends. Flush and clear every `batch_size` rows: memory stays at +50 entities, the batches stay full, and it is still one transaction (flush is not commit). + +**Assigned ids (Task 7).** Spring Data's `save` calls `persist` only when `isNew()` is true, and by +default that means "the id is null". A UUID made in the constructor is never null, so every save is a +`merge`: a SELECT to look for the row, then the INSERT. Implement `Persistable` (new until +`@PostPersist` or `@PostLoad`), or add a `@Version Long`, or let Hibernate generate the UUID. + +**Leaving JPA (Task 8).** `JdbcTemplate.batchUpdate`: no entities, no persistence context, 200 round +trips for 10,000 rows. `COPY ... FROM STDIN` through the driver's `CopyManager`: one statement for any +number of rows, but you write the CSV yourself (quote every field), there are no cascades, ids or +lifecycle callbacks, and one bad row fails the whole load. + +**When to use which.** + +| | JPA, batched | JdbcTemplate.batchUpdate | COPY | +|---|---|---|---| +| 10,000 rows | 401 round trips | 200 round trips | 1 | +| Entities, cascades, callbacks, `@Version` | Yes | No | No | +| Memory | Flush and clear, or it grows with the file | Only your rows | Only what you stream | +| One bad row | The whole transaction rolls back | The whole transaction rolls back | The whole COPY fails | +| Use it for | Normal business writes, hundreds to tens of thousands of rows | Big imports into simple tables | Bulk loads: migrations, nightly feeds, millions of rows | + +
diff --git a/java/concepts/junior-mid/16-batch-writes/TASKS_GUIDED.md b/java/concepts/junior-mid/16-batch-writes/TASKS_GUIDED.md new file mode 100644 index 0000000..1356c43 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/TASKS_GUIDED.md @@ -0,0 +1,895 @@ +# Guided Tasks — Batch Writes + +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`. + +Times will differ on your machine, and from run to run. The counts and the `RESULT` lines should +match. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +--- + +## Task 1: See 10,000 Round Trips + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +``` +Strategy: batched | rows: 10,000 +Settings: hibernate.jdbc.batch_size=50 | order_inserts=false | order_updates=false | reWriteBatchedInserts=false +Product ids: IDENTITY. Postgres makes each id while it runs the INSERT + +IMPORT: 10,000 new products +=========================== + +What the application sent, counted at the JDBC driver (one execute or executeBatch = one round trip) + round trips rows batches (count x size) statement + ----------- ------ ---------------------- --------------------------------------------------- + 10,000 10,000 insert into product (name,price,sku) values (?,?,?) + +What Postgres executed, counted by the server (pg_stat_statements) + executions rows rows each statement + ---------- ------ --------- ------------------------------------------------------------------ + 10,000 10,000 1 insert into product (name,price,sku) values ($1,$2,$3) RETURNING * + +Round trips: 10,000 +Commits: 1 +Peak entities held: 10,000 (the most entities in Hibernate's persistence context at one flush) +Time taken: 4,351 ms + +Rows in the database: 10,000 products, 0 stock levels, 0 price changes + +RESULT: 10,000 ROUND TRIPS. The import wrote 10,000 rows, 1.0 per round trip. +RESULT: 10,000 ENTITIES IN MEMORY. The persistence context held the whole import until it ended. +``` + +Read it top to bottom: + +- **`hibernate.jdbc.batch_size=50`** is set. Batching is "on". +- **10,000 round trips, 1 row each.** Not one batch. Every INSERT went to Postgres on its own, and the + application waited for the answer before sending the next one. +- **`RETURNING *`.** You did not write that. The Postgres driver added it to read back the id that + Postgres generated. Keep that in mind: it is the whole story of Task 2. +- **10,000 entities held.** Every product of the import was still in Hibernate's memory at the end. + That is Task 6. + +### Why one round trip per row is slow + +A round trip is: the application sends a statement, the network carries it, Postgres parses and runs +it, the answer travels back, and only then is the next one sent. On your laptop that is a fraction +of a millisecond. To a database in another data centre it is 1 or 2 ms, and 10,000 of them are 10 to +20 seconds of waiting, during which neither side is doing any work. + +`./demo --sql` lists the first 25 round trips: every one is `single 1 row`. A plain +`executeUpdate()`: Hibernate did not even build a JDBC batch. + +### The worst case + +```bash +./demo --strategy one-by-one +``` + +``` +Round trips: 10,000 +Commits: 10,000 +Time taken: 13,246 ms + +RESULT: 10,000 COMMITS. Every row was its own transaction. +RESULT: 10,000 ROUND TRIPS. The import wrote 10,000 rows, 1.0 per round trip. +``` + +`importOneByOne` calls `products.save(...)` in a loop with no `@Transactional` around it, so every +`save` is its own transaction. A commit waits until Postgres has written the transaction to disk, so +10,000 commits are 10,000 disk flushes. Three times slower again. And if row 5,000 is bad, rows 1 to +4,999 stay in the database: half an import. + +### Check + +```bash +./check 1 +``` + +``` +Task 1: See 10,000 round trips + [PASS] One by one: 500 rows are 500 INSERTs, each in its own round trip and its own transaction (this documents the problem) + [PASS] One by one: a bad row in the middle leaves every row before it in the database (this documents the problem) + 2 of 2 pass +``` + +These pass on purpose. `importOneByOne` stays as it is, so you can always compare against it. + +--- + +## Task 2: Let Hibernate Batch: SEQUENCE Instead of IDENTITY + +### Why IDENTITY turns batching off + +Open `Product`: + +```java +@Id +@GeneratedValue(strategy = GenerationType.IDENTITY) +private Long id; +``` + +`IDENTITY` means: Postgres makes the id while it runs the INSERT. But Hibernate needs the id the moment +you call `persist`, because it keeps every managed entity in the persistence context under its id. So +it cannot wait to put the INSERT in a batch: it has to run it **now**, alone, and read the id back. +That is the `RETURNING *`. Hibernate quietly turns insert batching off for every entity with an +IDENTITY id. No warning, no log line. + +The fix is to get the ids **before** the INSERTs, from a sequence. + +### Step 1: a sequence in `schema.sql` + +Replace the start of the `product` table: + +```sql +-- Postgres makes each id while it runs the INSERT. +create table product ( + id bigint primary key generated by default as identity, +``` + +with: + +```sql +create sequence product_seq increment by 50; + +create table product ( + id bigint primary key default nextval('product_seq'), +``` + +`schema.sql` drops and creates everything on every start, so the change applies the next time you run. +The column default means plain SQL inserts (Task 8) still get an id. + +### Step 2: the entity + +```java +@Id +@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_ids") +@SequenceGenerator(name = "product_ids", sequenceName = "product_seq", allocationSize = 50) +private Long id; +``` + +Import `jakarta.persistence.SequenceGenerator`, and replace the TODO comment above the id with one of +your own: what does the 50 mean? + +### Look before you go on: the two numbers must agree + +`allocationSize = 50` says: "one `nextval` gives me 50 ids". `increment by 50` says: "every `nextval` +moves the sequence on by 50". If they disagree, Hibernate 7 refuses to start. With +`create sequence product_seq;` (increment 1) you get: + +``` +Caused by: org.hibernate.MappingException: The increment size of the [product_seq] sequence is set to [50] in the entity mapping but the mapped database sequence increment size is [1] +``` + +And if both are 1 (`allocationSize = 1`, the sequence left at 1), it starts, and does this: + +``` + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------- + 10,000 10,000 select nextval('product_seq') + 200 10,000 200 x 50 insert into product (name,price,sku,id) values (?,?,?,?) + +RESULT: 10,200 ROUND TRIPS. The import wrote 10,000 rows, 1.0 per round trip. +``` + +The INSERTs are batched, and a SELECT per row has taken their place. That is why the 50 matters. + +### After + +```bash +./demo +``` + +``` +Product ids: SEQUENCE product_seq, allocationSize 50 (PooledOptimizer: one nextval per 50 ids) + + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------- + 201 201 select nextval('product_seq') + 200 10,000 200 x 50 insert into product (name,price,sku,id) values (?,?,?,?) + +Round trips: 401 +Peak entities held: 10,000 (the most entities in Hibernate's persistence context at one flush) +Time taken: 1,266 ms + +RESULT: 10,000 ENTITIES IN MEMORY. The persistence context held the whole import until it ended. +``` + +10,000 round trips down to 401: 200 batches of 50, and one `nextval` per 50 ids. The INSERT now +includes the `id` column, because Hibernate knows it in advance. The memory line stays until Task 6. + +```bash +./check 2 +``` + +4 of 4 pass. + +--- + +## Task 3: Inspect the Batches and the Sequence + +### Step 1: when are the INSERTs sent? + +```bash +./demo --sql +``` + +``` +The first 25 round trips, in the order they were sent + 1 single 1 row select nextval('product_seq') + 2 single 1 row select nextval('product_seq') + 3 single 1 row select nextval('product_seq') + ... + 25 single 1 row select nextval('product_seq') +``` + +All 201 `nextval` calls come first. `saveAll` calls `persist` for every product, and `persist` +only needs an id: no SQL is sent for the product itself. The INSERTs are written when the persistence +context is **flushed**, and here that happens once, at commit. Then all 200 batches go out together. + +### Step 2: the sequence + +```bash +./inspect +``` + +``` +WHERE EACH TABLE GETS ITS IDS (information_schema.columns) + table type where the id comes from + ------------ ------ ---------------------------------------------------- + price_change uuid none: the application must send it + product bigint DEFAULT nextval('product_seq'::regclass) + stock_level bigint IDENTITY: Postgres makes it while it runs the INSERT + +SEQUENCES (pg_sequences) + sequence increment by last value handed out + ------------------ ------------ --------------------- + product_seq 50 10001 + stock_level_id_seq 1 (never used) + +THE ROWS AND THEIR IDS + table rows lowest id highest id most common gaps between neighbouring ids + ------------ ------ --------- ---------- ----------------------------------------- + price_change 0 + product 10,000 1 10000 +1 (9,999x) + stock_level 0 + +WHAT POSTGRES EXECUTED FOR THE LAST REQUEST OF ./demo (pg_stat_statements) + executions rows rows each statement + ---------- ------ --------- ------------------------------------------------------------ + 10,000 10,000 1 insert into product (name,price,sku,id) values ($1,$2,$3,$4) + 201 201 1 select nextval($1) +``` + +How the **pooled optimizer** uses the sequence: each `nextval` returns the **top** of a block of 50, +and Hibernate hands out the 50 ids below it from memory. The very first call is special: a fresh +sequence answers 1, which cannot be the top of a block, so Hibernate calls again (51) and uses 1 to +51. After that it is one call per 50 ids: 2 + 199 = 201 calls, and the last one returned 10,001, +the top of a block whose last id was not needed. + +Two consequences worth saying in an interview: + +- **Other writers are safe.** A plain `INSERT` with the column default takes the next value, say + 10,051, and uses it as an id. Hibernate's next block is the one *below* its next value, 10,052 to + 10,101. The two never meet. `SequenceIdsIT.idsNeverClash` proves it. +- **Gaps are normal.** When the application stops, the unused ids of its current block are gone. + Sequences never go back either, not even on rollback. An id identifies a row; it does not count rows. + +`stock_level_id_seq` is the sequence behind the identity column of `stock_level`: an identity column +uses a sequence too, but Postgres calls it during the INSERT, which is exactly the problem. + +### Step 3: what a batch saves, and what it does not + +Look at the last table again: the application made **200** INSERT round trips, and Postgres +executed **10,000** INSERT statements. A JDBC batch puts 50 statements in one network message. It +saves the waiting. Postgres still executes each row as its own statement. Task 4 fixes that. + +--- + +## Task 4: Multi-Row INSERTs: `reWriteBatchedInserts` + +### The change + +In `application.properties`, add the option to the JDBC URL: + +```properties +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5455/batching?reWriteBatchedInserts=true} +``` + +That is all. It is an option of the Postgres JDBC driver, not of Hibernate. + +(A `DB_URL` environment variable replaces this URL, option included. The tests copy everything after +`?` onto their own database's URL. Or: `spring.datasource.hikari.data-source-properties.reWriteBatchedInserts=true`.) + +### After + +```bash +./demo +``` + +``` +Settings: hibernate.jdbc.batch_size=50 | order_inserts=false | order_updates=false | reWriteBatchedInserts=true + +What Postgres executed, counted by the server (pg_stat_statements) + executions rows rows each statement + ---------- ----- --------- ---------------------------------------------------------------- + 201 201 1 select nextval($1) + 200 400 2 insert into product (name,price,sku,id) values ($1,$2,$3,$4),... + 200 3,200 16 insert into product (name,price,sku,id) values ($1,$2,$3,$4),... + 200 6,400 32 insert into product (name,price,sku,id) values ($1,$2,$3,$4),... + +Round trips: 401 +Time taken: 672 ms +``` + +The application still sends 200 batches of 50: Hibernate did not change. The **driver** rewrote each +batch of 50 single-row INSERTs into three multi-row INSERTs, of 32, 16 and 2 rows: + +```sql +insert into product (name,price,sku,id) values ($1,$2,$3,$4),($5,$6,$7,$8),... +``` + +10,000 executions became 600. The sizes are powers of two, which keeps the number of different +statements Postgres has to prepare small. + +Compare with the option off, for one run: + +```bash +./demo --rewrite off +``` + +Same 401 round trips, 10,000 executions on the server, and slower (about 1,150 ms against 650 ms in +one run on a laptop). + +```bash +./check 4 +``` + +3 of 3 pass. + +--- + +## Task 5: Parents and Children: `order_inserts` and `order_updates` + +### Before + +```bash +./demo --stock +``` + +``` +Product ids: SEQUENCE product_seq, allocationSize 50 (PooledOptimizer: one nextval per 50 ids) +StockLevel ids: IDENTITY. Postgres makes each id while it runs the INSERT + +IMPORT: 10,000 new products, each with 3 stock levels + round trips rows batches (count x size) statement + ----------- ------ ---------------------- ---------------------------------------------------------------------- + 201 201 select nextval('product_seq') + 10,000 10,000 10,000 x 1 insert into product (name,price,sku,id) values (?,?,?,?) + 30,000 30,000 insert into stock_level (product_id,quantity,warehouse) values (?,?,?) + +Round trips: 40,201 +RESULT: 40,201 ROUND TRIPS. The import wrote 40,000 rows, 1.0 per round trip. +``` + +`Product` uses a sequence now, and its INSERTs are still sent one at a time ("10,000 x 1"). The stock +levels use IDENTITY, so each one must be inserted at once. But a stock level points to its product +(a foreign key), so the product's INSERT has to be sent first: Hibernate sends the product's "batch" +of 1 every time. **One IDENTITY child breaks the batching of its parent too.** + +### Step 1: stock levels on a sequence too + +In `schema.sql`, add `create sequence stock_level_seq increment by 50;` after the product sequence, +and in the `stock_level` table: + +```sql + id bigint primary key default nextval('stock_level_seq'), +``` + +In `StockLevel`, replace the TODO and the id: + +```java +@Id +@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "stock_level_ids") +@SequenceGenerator(name = "stock_level_ids", sequenceName = "stock_level_seq", allocationSize = 50) +private Long id; +``` + +```bash +./demo --stock +``` + +``` + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------------------------- + 201 201 select nextval('product_seq') + 601 601 select nextval('stock_level_seq') + 10,000 10,000 10,000 x 1 insert into product (name,price,sku,id) values (?,?,?,?) + 10,000 30,000 10,000 x 3 insert into stock_level (product_id,quantity,warehouse,id) values (?,?,... + +Round trips: 20,802 + +RESULT: 20,802 ROUND TRIPS. The import wrote 40,000 rows, 1.9 per round trip. +RESULT: 40,000 ENTITIES IN MEMORY. The persistence context held the whole import until it ended. +RESULT: 20,113 ROUND TRIPS. The update wrote 40,000 rows, 2.0 per round trip. +``` + +Better, and still batches of 1 and 3. Look at the order: + +```bash +./demo --stock --sql --rows 100 +``` + +``` + 11 batch 1 row insert into product (name,price,sku,id) values (?,?,?,?) + 12 batch 3 rows insert into stock_level (product_id,quantity,warehouse,id) values (?,?,... + 13 batch 1 row insert into product (name,price,sku,id) values (?,?,?,?) + 14 batch 3 rows insert into stock_level (product_id,quantity,warehouse,id) values (?,?,... +``` + +A JDBC batch is **one statement with many sets of values**. Hibernate writes the INSERTs in the order +the entities were persisted: product 1, its 3 stock levels, product 2, its 3 stock levels... Every +time the statement changes, the batch so far is sent and a new one begins. + +### Step 2: sort by table + +In `application.properties`, under `batch_size`: + +```properties +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +``` + +```bash +./demo --stock +``` + +``` +IMPORT: 10,000 new products, each with 3 stock levels + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------------------------- + 201 201 select nextval('product_seq') + 601 601 select nextval('stock_level_seq') + 200 10,000 200 x 50 insert into product (name,price,sku,id) values (?,?,?,?) + 600 30,000 600 x 50 insert into stock_level (product_id,quantity,warehouse,id) values (?,?,... +Round trips: 1,602 + +UPDATE: the next day's feed, a new price and new stock for every product + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------------------------- + 10 10 select distinct p1_0.id,p1_0.name,p1_0.price,p1_0.sku,sl1_0.product_id,... + 200 10,000 200 x 50 update product set name=?,price=?,sku=? where id=? + 600 30,000 600 x 50 update stock_level set product_id=?,quantity=?,warehouse=? where id=? + +What Postgres executed, counted by the server (pg_stat_statements) + executions rows rows each statement + ---------- ------ --------- -------------------------------------------------------------------------- + 30,000 30,000 1 update stock_level set product_id=$1,quantity=$2,warehouse=$3 where id=$4 + 10,000 10,000 1 update product set name=$1,price=$2,sku=$3 where id=$4 +Round trips: 810 +``` + +`order_inserts` sorts the INSERTs of a flush by table (parents still before their children), and +`order_updates` does the same for UPDATEs. Before, the update took 20,113 round trips, with the same +alternating problem; now 810. + +Two more things in that output: + +- **UPDATEs are not rewritten.** Postgres executed 30,000 single-row UPDATEs. `reWriteBatchedInserts` + does what its name says. +- **`update product set name=?,price=?,sku=?`** sends every column, not just the price. That is + Hibernate's default: one UPDATE statement per entity, the same every time, so it batches well. + +```bash +./check 5 +``` + +4 of 4 pass. + +--- + +## Task 6: Flat Memory: Flush and Clear + +### Before + +```bash +./demo --rows 100000 +``` + +``` +Round trips: 4,001 +Peak entities held: 100,000 (the most entities in Hibernate's persistence context at one flush) +Time taken: 4,994 ms + +RESULT: 100,000 ENTITIES IN MEMORY. The persistence context held the whole import until it ended. +``` + +`ProductImporter.importBatched` puts every product in a list and calls `saveAll(all)`. Two things +hold every row: + +- the `all` list, and +- the **persistence context**. Every entity you persist stays managed until the transaction ends, + together with a snapshot of its values that Hibernate compares at flush time (dirty checking). At + commit Hibernate walks all 100,000 of them. + +Memory grows with the file, and a big enough feed ends in an `OutOfMemoryError`. The rows arrive one +at a time (the CSV is read as a stream), so there is no reason to keep them. + +### The fix + +```java +@Transactional +public int importBatched(Iterable rows) { + List chunk = new ArrayList<>(batchSize); + int count = 0; + for (ProductRow row : rows) { + chunk.add(Product.from(row)); + count++; + if (chunk.size() == batchSize) { + saveAndForget(chunk); + } + } + saveAndForget(chunk); + return count; +} + +private void saveAndForget(List chunk) { + products.saveAll(chunk); + entityManager.flush(); + entityManager.clear(); + chunk.clear(); +} +``` + +Replace the whole method (and its TODO comment). `entityManager` and `batchSize` are already fields. + +- **`flush()`** sends the pending INSERTs: exactly one batch of 50. +- **`clear()`** makes Hibernate forget every entity it manages. Never clear without flushing first: + the pending INSERTs are thrown away. Tried: the import answered 200 and stored 0 rows. +- **The chunk is `batchSize`.** Clear every 30 rows and every batch is 30 rows. + +### After + +```bash +./demo +``` + +``` + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------- + 201 201 select nextval('product_seq') + 200 10,000 200 x 50 insert into product (name,price,sku,id) values (?,?,?,?) + +Round trips: 401 +Peak entities held: 50 (the most entities in Hibernate's persistence context at one flush) + +RESULT: OK. 10,000 rows in 401 round trips, at most 50 entities in memory. +``` + +`./demo --sql` now shows `nextval`, a batch of 50, `nextval`, a batch of 50: the INSERTs go out as +the file is read, not at the end. `./demo --rows 100000` holds 50 entities and took 2,811 ms instead +of 4,994: there is nothing left to dirty-check at commit. `./demo --stock` holds at most 200 (50 +products and their 150 stock levels). + +### Flush is not commit + +It is still **one transaction**. `flush()` sends SQL inside the transaction; only the commit at the +end makes it permanent. `PersistenceContextIT.flushIsNotCommit` puts a negative price in row 1,901: +the first 1,900 rows have been flushed, and the import still leaves nothing behind. + +If you committed every 50 rows instead, memory would be the same, and a failed import would leave +half a feed in the table (Task 1's one-by-one problem, in bigger pieces). Sometimes that is what you +want, with a record of how far you got. It is a decision, not a free optimisation. + +### And `StatelessSession`? + +Hibernate's `StatelessSession` has no persistence context at all: `insert(entity)` sends the INSERT +and forgets the entity. It also has no cascades (you insert the stock levels yourself) and no dirty +checking. Run on Hibernate 7.2 it **does not batch**: 2,000 products were 2,000 INSERT round trips +until `session.setJdbcBatchSize(50)` was called. Flush and clear keeps everything JPA gives you. + +```bash +./check 6 +``` + +4 of 4 pass. + +--- + +## Task 7: Ids Made in Java: No SELECT Before Every INSERT + +### Before + +```bash +./demo --prices +``` + +``` +PriceChange ids: assigned in Java: Hibernate generates nothing + + round trips rows batches (count x size) statement + ----------- ------ ---------------------- -------------------------------------------------------------------------- + 10,000 10,000 select pc1_0.id,pc1_0.changed_at,pc1_0.price,pc1_0.sku from price_chang... + 200 10,000 200 x 50 insert into price_change (changed_at,price,sku,id) values (?,?,?,?) + +What Postgres executed, counted by the server (pg_stat_statements) + executions rows rows each statement + ---------- ----- --------- -------------------------------------------------------------------------- + 10,000 0 0 select pc1_0.id,pc1_0.changed_at,pc1_0.price,pc1_0.sku from price_chang... + +Round trips: 10,200 +RESULT: 10,000 SELECTS. saveAll() looked up every price change before inserting it. +``` + +10,000 SELECTs, each finding 0 rows, that nobody wrote. + +### Why + +`saveAll` calls `save` for each entity, and `SimpleJpaRepository.save` is: + +```java +if (entityInformation.isNew(entity)) { + entityManager.persist(entity); + return entity; +} else { + return entityManager.merge(entity); +} +``` + +For an entity without `@Version`, Spring Data decides "new" by looking at the id: null means new. +`PriceChange` sets `id = UUID.randomUUID()` in its constructor, so the id is never null, Spring Data +thinks it may already exist, and calls `merge`. `merge` must find out, so it SELECTs by id, finds +nothing, and then inserts a **copy** of your object (`saveAll` returns the copies). + +### The fix + +Let the entity say whether it is new. In `PriceChange`: + +```java +public class PriceChange implements Persistable { +``` + +```java +@Transient +private boolean isNew = true; +``` + +and replace `getId()` with: + +```java +@Override +public UUID getId() { + return id; +} + +@Override +public boolean isNew() { + return isNew; +} + +@PostPersist +@PostLoad +void markNotNew() { + isNew = false; +} +``` + +Imports: `jakarta.persistence.PostLoad`, `jakarta.persistence.PostPersist`, +`jakarta.persistence.Transient` and `org.springframework.data.domain.Persistable`. Replace the TODO +comment. + +**Why `@PostLoad` matters:** a price change read from the database is not new. Without `@PostLoad` +it would still say `isNew() == true`, and saving it again would `persist` it a second time. Tried: +`duplicate key value violates unique constraint "price_change_pkey"`. +`PriceHistoryIT.aLoadedPriceChangeIsUpdated` catches it. + +### After + +```bash +./demo --prices +``` + +``` + round trips rows batches (count x size) statement + ----------- ------ ---------------------- ------------------------------------------------------------------- + 200 10,000 200 x 50 insert into price_change (changed_at,price,sku,id) values (?,?,?,?) + +RESULT: OK. 10,000 rows in 200 round trips. +``` + +No sequence, no SELECT: 200 round trips for 10,000 rows. + +### Two other fixes that also work + +Both were tried and pass all three Task 7 tests: + +- **`@Version private Long version;`** (and a `version bigint` column). With a version attribute + Spring Data decides "new" by the version instead of the id: `null` means new. You get optimistic + locking on top. +- **`@Id @GeneratedValue private UUID id;`** and no `UUID.randomUUID()` in the constructor. Hibernate + makes the UUID in memory at `persist`, so the id is null until then. The demo's header then names + Hibernate's `UuidGenerator`. + +```bash +./check 7 +``` + +3 of 3 pass. + +--- + +## Task 8: Leave JPA: JdbcTemplate and COPY, Then Compare + +### Before + +```bash +./demo --strategy jdbc +``` + +``` + 10,000 10,000 insert into product (sku, name, price) values (?, ?, ?) +RESULT: 10,000 ROUND TRIPS. The import wrote 10,000 rows, 1.0 per round trip. +``` + +No Hibernate in sight, and the same problem: `jdbc.update(...)` in a loop is one round trip per row. + +### Step 1: `JdbcTemplate.batchUpdate` + +In `JdbcProductImporter`, replace `batchInsert` (and its TODO comment): + +```java +@Transactional +public int batchInsert(Iterable rows) { + List chunk = new ArrayList<>(batchSize); + int count = 0; + for (ProductRow row : rows) { + chunk.add(row); + count++; + if (chunk.size() == batchSize) { + insert(chunk); + } + } + insert(chunk); + return count; +} + +private void insert(List chunk) { + if (chunk.isEmpty()) { + return; + } + jdbc.batchUpdate(INSERT, chunk, chunk.size(), (statement, row) -> { + statement.setString(1, row.sku()); + statement.setString(2, row.name()); + statement.setBigDecimal(3, row.price()); + }); + chunk.clear(); +} +``` + +The same chunking as Task 6, for the same reason: the rows stream in and never all sit in memory. +The id comes from the column default you wrote in Task 2. + +### Step 2: COPY that survives a comma + +```bash +./demo --strategy copy +``` + +``` + 1 10,000 1 x 10,000 copy product (sku, name, price) from stdin with (format csv) +RESULT: OK. 10,000 rows in 1 round trip. +``` + +One statement for 10,000 rows. And `./check 8` still fails: + +``` + [FAIL] COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent + COPY refused the rows: ERROR: invalid input syntax for type numeric: " large\0.5 l" + Where: COPY product, line 1, column price: " large\0.5 l" +``` + +The CSV line is built with `row.name()` as it is. A comma in the name makes a fourth column, and +Postgres tries to read `"large"\0.5 l` as the price. In CSV format a field in double quotes may hold +commas and line breaks, and a quote inside it is written twice. Add to the class: + +```java +private static String csv(String value) { + return "\"" + value.replace("\"", "\"\"") + "\""; +} +``` + +and build the line with it: + +```java +byte[] line = (csv(row.sku()) + "," + csv(row.name()) + "," + row.price().toPlainString() + "\n") + .getBytes(StandardCharsets.UTF_8); +``` + +Replace the TODO comment of `copy`. + +```bash +./check 8 +./check +``` + +`./check` prints 32 of 32. + +### Step 3: compare + +Numbers from one laptop run. Your times will differ; the shape will not. + +| 10,000 rows | Round trips | Statements Postgres executed | Commits | Time | +|---|---|---|---|---| +| `--strategy one-by-one` | 10,201 | 10,000 INSERTs | 10,000 | 13.1 s | +| `--rewrite off` (JPA, batched) | 401 | 10,000 INSERTs | 1 | 1.2 s | +| default (JPA, batched, rewritten) | 401 | 600 INSERTs | 1 | 0.6 s | +| `--strategy jdbc` | 200 | 600 INSERTs | 1 | 0.2 s | +| `--strategy copy` | 1 | 1 COPY | 1 | 0.1 s | + +| 100,000 rows | Round trips | Statements Postgres executed | Time | +|---|---|---|---| +| `--rewrite off` | 4,001 | 100,000 | 4.0 s | +| default | 4,001 | 6,000 | 3.0 s | +| `--strategy jdbc` | 2,000 | 6,000 | 1.4 s | +| `--strategy copy` | 1 | 1 | 0.4 s | + +What JDBC and COPY give up, honestly: + +- **No entity lifecycle.** No cascades (`./demo --stock --strategy jdbc` refuses: nothing would write + the stock levels), no callbacks, no `@Version`, no dirty checking. You write the SQL or the CSV. +- **Ids** come from the column default, and every plain `nextval` jumps 50: after + `./demo --strategy jdbc`, `./inspect` shows gaps of `+50` between neighbouring ids. Harmless. +- **One bad row.** A negative price in row 1,501 and COPY stores nothing at all + (`JdbcImportIT.oneBadRowStopsTheWholeCopy`), like the one-transaction imports. For "load what you + can", validate first, or COPY into a staging table without constraints and move the good rows with + one `INSERT ... SELECT`. +- **Transaction size.** One transaction for 1,000,000 rows keeps everything uncommitted to the very + end: fine for a nightly feed into its own table, worth a thought next to live traffic. + +### When to use which + +| | JPA, batched | JdbcTemplate.batchUpdate | COPY | +|---|---|---|---| +| You need | Entities, cascades, callbacks, `@Version` | Plain rows, plain SQL | Raw speed for a bulk load | +| Settings that matter | SEQUENCE ids, `batch_size`, `order_inserts`, `order_updates`, flush and clear | Batch size, `reWriteBatchedInserts` | Correct CSV quoting | +| Use it for | Everyday writes, imports up to tens of thousands of rows | Big imports into simple tables | Migrations, nightly feeds, millions of rows | + +### How to say it in an interview + +> "Batching in Hibernate needs three things. The ids must be known before the INSERT, so a SEQUENCE +> with a pooled `allocationSize` that matches the sequence's increment, never IDENTITY, because +> Hibernate silently turns insert batching off for IDENTITY. Then `hibernate.jdbc.batch_size`, and +> `order_inserts` and `order_updates` so parents and children do not take turns and break every batch. +> On Postgres I add `reWriteBatchedInserts=true` so the driver sends multi-row INSERTs. For a big +> import I flush and clear every batch so the persistence context stays small, and it is still one +> transaction, because flush is not commit. If the entities have ids assigned in Java, I make sure +> `save` does not merge, with `Persistable` or a version field. And for a real bulk load I leave JPA: +> `JdbcTemplate.batchUpdate`, or `COPY`, which loads 100,000 rows in one statement, at the price of +> no entity lifecycle and all-or-nothing on a bad row." + +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/16-batch-writes/solution/.mvn/jvm.config b/java/concepts/junior-mid/16-batch-writes/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/16-batch-writes/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/solution/check b/java/concepts/junior-mid/16-batch-writes/solution/check new file mode 100755 index 0000000..8ecf048 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/check.cmd b/java/concepts/junior-mid/16-batch-writes/solution/check.cmd new file mode 100644 index 0000000..3c5f22a --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/compose.yaml b/java/concepts/junior-mid/16-batch-writes/solution/compose.yaml new file mode 100644 index 0000000..b4d4314 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/compose.yaml @@ -0,0 +1,21 @@ +# 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: batch-writes +services: + postgres: + image: postgres:17-alpine + container_name: batch-writes-postgres + # pg_stat_statements counts every statement Postgres executes. ./demo and ./inspect read it to + # show what the database really received, which is not always what the application sent. + command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "pg_stat_statements.track=all"] + environment: + POSTGRES_DB: batching + POSTGRES_USER: batching + POSTGRES_PASSWORD: batching + ports: + - "5455:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U batching -d batching"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/16-batch-writes/solution/demo b/java/concepts/junior-mid/16-batch-writes/solution/demo new file mode 100755 index 0000000..4b092c3 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/demo.cmd b/java/concepts/junior-mid/16-batch-writes/solution/demo.cmd new file mode 100644 index 0000000..4c7d257 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/inspect b/java/concepts/junior-mid/16-batch-writes/solution/inspect new file mode 100755 index 0000000..b86b2a6 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/inspect.cmd b/java/concepts/junior-mid/16-batch-writes/solution/inspect.cmd new file mode 100644 index 0000000..fbf084b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/solution/mvnw b/java/concepts/junior-mid/16-batch-writes/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/solution/mvnw.cmd b/java/concepts/junior-mid/16-batch-writes/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/solution/pom.xml b/java/concepts/junior-mid/16-batch-writes/solution/pom.xml new file mode 100644 index 0000000..60b85e2 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + batch-writes + 0.0.1-SNAPSHOT + batch-writes + Batch writes: watch 10,000 rows take 10,000 round trips, then make JPA and JDBC batch them + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + + postgresql + + + + 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/16-batch-writes/solution/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java new file mode 100644 index 0000000..749a0b5 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching; + +import com.amigoscode.batching.imports.BadCsvException; +import com.amigoscode.batching.imports.ImportStrategy.UnknownStrategyException; +import org.springframework.dao.DataIntegrityViolationException; +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 becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + /** {@code line} is the line of the CSV file that was rejected, or null. */ + public record ApiError(String code, String message, Integer line) { + } + + @ExceptionHandler(BadCsvException.class) + public ResponseEntity badCsv(BadCsvException e) { + return ResponseEntity.badRequest().body(new ApiError("BAD_CSV", e.getMessage(), e.line())); + } + + @ExceptionHandler(UnknownStrategyException.class) + public ResponseEntity unknownStrategy(UnknownStrategyException e) { + return ResponseEntity.badRequest().body(new ApiError("UNKNOWN_STRATEGY", e.getMessage(), null)); + } + + /** A row the database refused, for example a negative price or a SKU that already exists. */ + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity rejected(DataIntegrityViolationException e) { + String reason = e.getMostSpecificCause().getMessage(); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiError("IMPORT_REJECTED", + "Nothing was imported: the database refused a row. " + firstLine(reason), null)); + } + + private static String firstLine(String text) { + return text == null ? "" : text.lines().findFirst().orElse(""); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java new file mode 100644 index 0000000..29f0898 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/BatchingApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.batching; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BatchingApplication { + + public static void main(String[] args) { + SpringApplication.run(BatchingApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java new file mode 100644 index 0000000..107e080 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/ManagedEntities.java @@ -0,0 +1,39 @@ +package com.amigoscode.batching.db; + +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; +import org.hibernate.Interceptor; + +/** + * Remembers the largest number of entities the persistence context held at any flush. Every + * entity Hibernate manages stays in memory, with a snapshot of its values for dirty checking, + * until the transaction ends or someone calls clear(). This makes that number visible. + * + *

Switched on in application.properties with hibernate.session_factory.interceptor. Hibernate + * calls preFlush with every entity in the persistence context, right before each flush. + * + *

A teaching tool: do not ship a static, shared counter like this in a real application. + */ +public class ManagedEntities implements Interceptor { + + private static final AtomicInteger PEAK = new AtomicInteger(); + + @Override + public void preFlush(Iterator entities) { + int count = 0; + while (entities.hasNext()) { + entities.next(); + count++; + } + PEAK.accumulateAndGet(count, Math::max); + } + + public static void reset() { + PEAK.set(0); + } + + /** The most entities the persistence context held at a flush since the last reset(). */ + public static int peak() { + return PEAK.get(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java new file mode 100644 index 0000000..b051e55 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/Recording.java @@ -0,0 +1,85 @@ +package com.amigoscode.batching.db; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** Everything the application sent to Postgres between SqlRecorder.start() and stop(). */ +public record Recording(List calls, int commits, int rollbacks) { + + /** One statement and everything that was sent with it. */ + public record Shape(String sql, int roundTrips, int rows, Map batchSizes) { + + /** + * "40 x 50" or "39 x 50, 1 x 17": how many batches of each size, biggest first. With more than + * three different sizes, "2,022 of 1 to 50 rows". Empty when nothing was batched. + */ + public String describeBatches() { + if (batchSizes.size() > 3) { + int batches = batchSizes.values().stream().mapToInt(Integer::intValue).sum(); + return String.format("%,d of %,d to %,d rows", batches, + batchSizes.keySet().stream().min(Integer::compare).orElseThrow(), + batchSizes.keySet().stream().max(Integer::compare).orElseThrow()); + } + List parts = new ArrayList<>(); + batchSizes.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(size -> parts.add(String.format("%,d x %,d", size.getValue(), size.getKey()))); + return String.join(", ", parts); + } + } + + public int roundTrips() { + return calls.size(); + } + + public int roundTrips(String sqlPrefix) { + return matching(sqlPrefix).size(); + } + + /** The number of rows (sets of values) sent with statements that start with the prefix. */ + public int rows(String sqlPrefix) { + return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).sum(); + } + + /** The biggest single round trip for statements that start with the prefix, in rows. */ + public int largestBatch(String sqlPrefix) { + return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).max().orElse(0); + } + + public List matching(String sqlPrefix) { + return calls.stream().filter(call -> call.startsWith(sqlPrefix)).toList(); + } + + /** The calls grouped by statement, in the order each statement was first sent. */ + public List shapes() { + Map> grouped = new LinkedHashMap<>(); + for (SqlCall call : calls) { + grouped.computeIfAbsent(call.shape(), ignored -> new ArrayList<>()).add(call); + } + List shapes = new ArrayList<>(); + grouped.forEach((sql, sameSql) -> { + Map batchSizes = new TreeMap<>(); + sameSql.stream() + .filter(call -> call.kind() != SqlCall.Kind.SINGLE) + .forEach(call -> batchSizes.merge(call.rows(), 1, Integer::sum)); + shapes.add(new Shape(sql, sameSql.size(), sameSql.stream().mapToInt(SqlCall::rows).sum(), batchSizes)); + }); + return shapes; + } + + /** A few lines for a failure message: what was sent, grouped by statement. */ + public String describe() { + StringBuilder text = new StringBuilder(String.format("%,d round trips:", roundTrips())); + for (Shape shape : shapes()) { + String sql = shape.sql().length() > 90 ? shape.sql().substring(0, 90) + "..." : shape.sql(); + text.append(String.format("%n%,d x %s", shape.roundTrips(), sql)); + if (!shape.batchSizes().isEmpty()) { + text.append(" [batches: ").append(shape.describeBatches()).append("]"); + } + } + return text.toString(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java new file mode 100644 index 0000000..592da9c --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlCall.java @@ -0,0 +1,29 @@ +package com.amigoscode.batching.db; + +import java.util.Locale; + +/** + * One round trip from the application to Postgres: one execute() of one statement, one + * executeBatch() of a JDBC batch, or one COPY. {@code rows} is how many sets of values it carried: + * 1 for a plain statement, the batch size for a batch, the number of rows for a COPY. + */ +public record SqlCall(String sql, Kind kind, int rows) { + + public enum Kind { + /** execute(), executeQuery() or executeUpdate(): one statement, one set of values. */ + SINGLE, + /** executeBatch(): the same statement with many sets of values, sent together. */ + BATCH, + /** COPY ... FROM STDIN: one statement, the rows stream after it. */ + COPY + } + + /** The statement in lower case, on one line. */ + public String shape() { + return sql.strip().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT); + } + + public boolean startsWith(String prefix) { + return shape().startsWith(prefix.toLowerCase(Locale.ROOT)); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java new file mode 100644 index 0000000..a68fd9c --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/db/SqlRecorder.java @@ -0,0 +1,219 @@ +package com.amigoscode.batching.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.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import javax.sql.DataSource; +import org.postgresql.PGConnection; +import org.postgresql.copy.CopyIn; +import org.postgresql.copy.CopyManager; +import org.postgresql.core.BaseConnection; +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 every round trip the application makes to Postgres, whoever makes it: Hibernate, Spring + * Data, JdbcTemplate or a COPY. ./demo and the tests use it to answer "how many times did this + * import talk to the database, and how many rows did each trip carry?" + * + * SqlRecorder.start(); + * ... run the import ... + * Recording recording = SqlRecorder.stop(); + * + * It wraps the DataSource, so it sees exactly what reaches the JDBC driver: one execute() is one + * round trip, one executeBatch() is one round trip however many rows were added to the batch. + * (Hibernate's own statement counters count a batch differently, which is why they are not used.) + * + *

A teaching tool: do not ship a static, shared recorder like this in a real application. + */ +public final class SqlRecorder { + + private static final Object LOCK = new Object(); + private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate"); + private static final Set EXECUTE_BATCH = Set.of("executeBatch", "executeLargeBatch"); + + private static List calls; + private static int commits; + private static int rollbacks; + + public static void start() { + synchronized (LOCK) { + calls = new ArrayList<>(); + commits = 0; + rollbacks = 0; + } + } + + /** Stops recording and returns what was sent since start(). */ + public static Recording stop() { + synchronized (LOCK) { + Recording recording = new Recording(calls == null ? List.of() : List.copyOf(calls), commits, rollbacks); + calls = null; + return recording; + } + } + + private static void record(String sql, SqlCall.Kind kind, int rows) { + synchronized (LOCK) { + if (calls != null) { + calls.add(new SqlCall(sql, kind, rows)); + } + } + } + + private static void recordEnd(boolean commit) { + synchronized (LOCK) { + if (calls != null) { + if (commit) { + commits++; + } else { + rollbacks++; + } + } + } + } + + /** 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 && !(bean instanceof RecordingDataSource) + ? 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) -> { + String name = method.getName(); + if (name.equals("unwrap") && args[0] == PGConnection.class) { + return watchCopy(connection.unwrap(PGConnection.class)); + } + Object result = call(connection, method, args); + if (name.equals("commit")) { + recordEnd(true); + } else if (name.equals("rollback") && args == null) { + recordEnd(false); + } else if (name.equals("prepareStatement") && result instanceof PreparedStatement statement) { + return watch(statement, (String) args[0]); + } else if (name.equals("createStatement") && result instanceof Statement statement) { + return watch(statement); + } + return result; + }); + } + + private static PreparedStatement watch(PreparedStatement statement, String sql) { + int[] batched = {0}; + return proxy(PreparedStatement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.equals("addBatch") && args == null) { + batched[0]++; + } else if (name.equals("clearBatch")) { + batched[0] = 0; + } else if (EXECUTE_BATCH.contains(name)) { + record(sql, SqlCall.Kind.BATCH, batched[0]); + batched[0] = 0; + } else if (EXECUTE.contains(name) && args == null) { + record(sql, SqlCall.Kind.SINGLE, 1); + } + return call(statement, method, args); + }); + } + + /** A plain Statement: the SQL is passed to execute() itself. */ + private static Statement watch(Statement statement) { + List batch = new ArrayList<>(); + return proxy(Statement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.equals("addBatch") && args != null) { + batch.add((String) args[0]); + } else if (EXECUTE_BATCH.contains(name) && !batch.isEmpty()) { + record(batch.getFirst(), SqlCall.Kind.BATCH, batch.size()); + batch.clear(); + } else if (EXECUTE.contains(name) && args != null && args[0] instanceof String sql) { + record(sql, SqlCall.Kind.SINGLE, 1); + } + return call(statement, method, args); + }); + } + + /** COPY does not go through a Statement at all: it is the driver's CopyManager. */ + private static PGConnection watchCopy(PGConnection connection) { + return proxy(PGConnection.class, (proxy, method, args) -> { + if (method.getName().equals("getCopyAPI")) { + return new RecordingCopyManager((BaseConnection) connection); + } + return call(connection, method, args); + }); + } + + private static T proxy(Class type, InvocationHandler handler) { + return type.cast(Proxy.newProxyInstance(SqlRecorder.class.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(); + } + } + } + + /** Records a COPY when it ends, with the number of rows Postgres says it stored. */ + private static final class RecordingCopyManager extends CopyManager { + + RecordingCopyManager(BaseConnection connection) throws SQLException { + super(connection); + } + + @Override + public CopyIn copyIn(String sql) throws SQLException { + CopyIn copy = super.copyIn(sql); + return RecordingDataSource.proxy(CopyIn.class, (proxy, method, args) -> { + Object result = RecordingDataSource.call(copy, method, args); + if (method.getName().equals("endCopy")) { + record(sql, SqlCall.Kind.COPY, (int) (long) (Long) result); + } + return result; + }); + } + + } + + private SqlRecorder() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java new file mode 100644 index 0000000..dce5c1a --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Db.java @@ -0,0 +1,52 @@ +package com.amigoscode.batching.demo; + +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. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5455/batching"); + static final String USER = env("DB_USER", "batching"); + static final String PASSWORD = env("DB_PASSWORD", "batching"); + + private Db() { + } + + /** + * A connection for the tools themselves. pg_stat_statements is told to ignore it, so the queries + * ./demo and ./inspect run to count things do not show up next to the application's statements. + */ + static Connection connect() throws SQLException { + Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); + try (Statement statement = connection.createStatement()) { + statement.execute("set pg_stat_statements.track = 'none'"); + } catch (SQLException notLoadedOrNotAllowed) { + // Without pg_stat_statements there is nothing to hide from. + } + return connection; + } + + /** 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/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java new file mode 100644 index 0000000..edd5b0e --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Demo.java @@ -0,0 +1,441 @@ +package com.amigoscode.batching.demo; + +import com.amigoscode.batching.BatchingApplication; +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlCall; +import com.amigoscode.batching.db.SqlRecorder; +import com.amigoscode.batching.price.PriceChange; +import com.amigoscode.batching.product.Product; +import com.amigoscode.batching.product.StockLevel; +import jakarta.persistence.EntityManagerFactory; +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.util.ArrayList; +import java.util.List; +import java.util.Locale; +import javax.sql.DataSource; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.generator.Generator; +import org.hibernate.id.IdentityGenerator; +import org.hibernate.id.enhanced.SequenceStyleGenerator; +import org.postgresql.core.BaseConnection; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; + +/** + * Starts the real application, sends it a generated CSV feed over HTTP, and prints how many round + * trips the import made to Postgres, what Postgres executed, and how many entities Hibernate held in + * memory. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final List STRATEGIES = List.of("one-by-one", "batched", "rewrite", "jdbc", "copy"); + private static final int WIDTH = 74; + + private record Options(String strategy, int rows, boolean stock, boolean prices, Boolean rewrite, boolean sql) { + + /** The strategy the application knows: "rewrite" is "batched" with the driver setting on. */ + String appStrategy() { + return strategy.equals("rewrite") ? "batched" : strategy; + } + + boolean jpa() { + return prices || !(strategy.equals("jdbc") || strategy.equals("copy")); + } + } + + /** One HTTP request and everything it caused. */ + private record Phase(String title, int status, String body, Recording recording, + List executed, int peakEntities, long millis) { + + int rowsWritten() { + return recording.calls().stream() + .filter(call -> call.startsWith("insert") || call.startsWith("update") || call.startsWith("copy")) + .mapToInt(SqlCall::rows) + .sum(); + } + } + + 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", + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always")); + Boolean rewrite = options.strategy().equals("rewrite") ? Boolean.TRUE : options.rewrite(); + + SpringApplication app = new SpringApplication(BatchingApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + if (rewrite != null) { + // An option on the URL beats a driver property, so the override goes on the URL itself. + app.addInitializers(context -> { + var environment = context.getEnvironment(); + String url = withRewrite(environment.getProperty("spring.datasource.url", Db.URL), rewrite); + environment.getPropertySources().addFirst(new MapPropertySource("demo-rewrite", + java.util.Map.of("spring.datasource.url", url))); + }); + } + try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) { + run(options, context); + } + } + + private static void run(Options options, ConfigurableApplicationContext context) throws Exception { + String baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + int batchSize = context.getEnvironment().getProperty("spring.jpa.properties.hibernate.jdbc.batch_size", Integer.class, 0); + + // A throwaway request first, so the import is not slowed down by start-up work. + http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding()); + + printHeader(options, context, batchSize); + + List phases = new ArrayList<>(); + try (Connection server = Db.connect()) { + boolean serverStats = ServerStats.available(server); + if (options.prices()) { + phases.add(send(http, server, serverStats, "PRICE HISTORY: " + number(options.rows()) + " price changes, saveAll()", + "POST", baseUrl + "/api/imports/prices", Feed.products(options.rows(), false))); + } else { + phases.add(send(http, server, serverStats, "IMPORT: " + number(options.rows()) + " new products" + + (options.stock() ? ", each with 3 stock levels" : ""), + "POST", baseUrl + "/api/imports/products?strategy=" + options.appStrategy(), + Feed.products(options.rows(), options.stock()))); + if (options.stock() && phases.getFirst().status() == 200) { + phases.add(send(http, server, serverStats, "UPDATE: the next day's feed, a new price and new stock for every product", + "PUT", baseUrl + "/api/imports/products", Feed.nextDay(options.rows()))); + } + } + if (!serverStats) { + System.out.println("(pg_stat_statements is not loaded in this Postgres, so the server side is not shown."); + System.out.println(" The compose.yaml of this project loads it: docker compose down, then docker compose up -d.)"); + System.out.println(); + } + } + + for (Phase phase : phases) { + print(phase, options.sql()); + } + + long products; + long stockLevels; + long priceChanges; + try (Connection connection = Db.connect()) { + products = count(connection, "product"); + stockLevels = count(connection, "stock_level"); + priceChanges = count(connection, "price_change"); + } + System.out.println("Rows in the database: " + number(products) + " products, " + number(stockLevels) + + " stock levels, " + number(priceChanges) + " price changes"); + System.out.println(); + + printResults(options, phases, batchSize, options.prices() ? priceChanges : products); + } + + private static long count(Connection connection, String table) throws java.sql.SQLException { + try (var statement = connection.createStatement(); var result = statement.executeQuery("select count(*) from " + table)) { + result.next(); + return result.getLong(1); + } + } + + private static Phase send(HttpClient http, Connection server, boolean serverStats, String title, + String method, String url, String csv) throws Exception { + HttpRequest request = HttpRequest.newBuilder(URI.create(url)) + .header("Content-Type", "text/csv") + .method(method, HttpRequest.BodyPublishers.ofString(csv)) + .build(); + if (serverStats) { + ServerStats.reset(server); + } + ManagedEntities.reset(); + SqlRecorder.start(); + long started = System.nanoTime(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + long millis = (System.nanoTime() - started) / 1_000_000; + Recording recording = SqlRecorder.stop(); + List executed = serverStats ? ServerStats.read(server) : List.of(); + return new Phase(title, response.statusCode(), response.body(), recording, executed, ManagedEntities.peak(), millis); + } + + /** The URL with reWriteBatchedInserts set to the given value, whatever it said before. */ + private static String withRewrite(String url, boolean on) { + String clean = url.replaceAll("(?i)([?&])reWriteBatchedInserts=[^&]*&?", "$1").replaceAll("[?&]$", ""); + return clean + (clean.contains("?") ? "&" : "?") + "reWriteBatchedInserts=" + on; + } + + private static void printHeader(Options options, ConfigurableApplicationContext context, int batchSize) { + // Ask the driver itself: the option can come from the URL or from a driver property. + String rewrite = "?"; + try (Connection connection = context.getBean(DataSource.class).getConnection()) { + rewrite = String.valueOf(connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled()); + } catch (Exception ignored) { + // Not the Postgres driver: leave it as "?". + } + var environment = context.getEnvironment(); + System.out.println(); + System.out.println("Strategy: " + options.strategy() + (options.prices() ? " (ignored: --prices always uses saveAll)" : "") + + " | rows: " + number(options.rows())); + System.out.println("Settings: hibernate.jdbc.batch_size=" + (batchSize == 0 ? "(not set)" : batchSize) + + " | order_inserts=" + environment.getProperty("spring.jpa.properties.hibernate.order_inserts", "false") + + " | order_updates=" + environment.getProperty("spring.jpa.properties.hibernate.order_updates", "false") + + " | reWriteBatchedInserts=" + rewrite); + SessionFactoryImplementor hibernate = context.getBean(EntityManagerFactory.class).unwrap(SessionFactoryImplementor.class); + if (options.prices()) { + System.out.println("PriceChange ids: " + describe(generator(hibernate, PriceChange.class))); + } else if (options.jpa()) { + System.out.println("Product ids: " + describe(generator(hibernate, Product.class))); + if (options.stock()) { + System.out.println("StockLevel ids: " + describe(generator(hibernate, StockLevel.class))); + } + } else { + System.out.println("Product ids: the column default, nextval('product_seq') or the identity. No entities."); + } + System.out.println(); + } + + private static Generator generator(SessionFactoryImplementor hibernate, Class entity) { + return hibernate.getMappingMetamodel().getEntityDescriptor(entity).getGenerator(); + } + + private static String describe(Generator generator) { + if (generator == null) { + return "assigned in Java: Hibernate generates nothing"; + } + if (generator instanceof IdentityGenerator) { + return "IDENTITY. Postgres makes each id while it runs the INSERT"; + } + if (generator instanceof SequenceStyleGenerator sequence) { + int allocation = sequence.getOptimizer().getIncrementSize(); + return "SEQUENCE " + sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText() + + ", allocationSize " + allocation + " (" + sequence.getOptimizer().getClass().getSimpleName() + + ": " + (allocation == 1 ? "one nextval per row" : "one nextval per " + allocation + " ids") + ")"; + } + String name = generator.getClass().getSimpleName(); + if (name.equals("UuidGenerator")) { + return "UuidGenerator. Hibernate makes a UUID in memory when the entity is persisted"; + } + return name.equals("Assigned") ? "assigned in Java: Hibernate generates nothing" : name; + } + + private static void print(Phase phase, boolean sql) { + System.out.println(phase.title()); + System.out.println("=".repeat(Math.min(phase.title().length(), WIDTH + 20))); + if (phase.status() != 200) { + System.out.println(); + System.out.println(" HTTP " + phase.status() + ": " + phase.body()); + System.out.println(); + return; + } + Recording recording = phase.recording(); + System.out.println(); + System.out.println("What the application sent, counted at the JDBC driver (one execute or executeBatch = one round trip)"); + List rows = new ArrayList<>(); + rows.add(new String[] {"round trips", "rows", "batches (count x size)", "statement"}); + for (Recording.Shape shape : recording.shapes()) { + rows.add(new String[] {number(shape.roundTrips()), number(shape.rows()), shape.describeBatches(), clip(shape.sql())}); + } + Table.print(rows, 0, 1); + if (sql) { + System.out.println(); + System.out.println("The first 25 round trips, in the order they were sent"); + List calls = recording.calls(); + for (int i = 0; i < Math.min(25, calls.size()); i++) { + SqlCall call = calls.get(i); + System.out.printf(" %4d %-6s %4d row%s %s%n", i + 1, call.kind().name().toLowerCase(Locale.ROOT), + call.rows(), call.rows() == 1 ? " " : "s", clip(call.shape())); + } + } + if (!phase.executed().isEmpty()) { + System.out.println(); + System.out.println("What Postgres executed, counted by the server (pg_stat_statements)"); + List executed = new ArrayList<>(); + executed.add(new String[] {"executions", "rows", "rows each", "statement"}); + for (ServerStats.Executed statement : phase.executed()) { + long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls(); + executed.add(new String[] {number(statement.calls()), number(statement.rows()), number(each), + clip(ServerStats.shorten(statement.query()))}); + } + Table.print(executed, 0, 1, 2); + } + System.out.println(); + System.out.println("Round trips: " + number(recording.roundTrips())); + System.out.println("Commits: " + number(recording.commits())); + System.out.println("Peak entities held: " + number(phase.peakEntities()) + + " (the most entities in Hibernate's persistence context at one flush)"); + System.out.println("Time taken: " + number(phase.millis()) + " ms"); + System.out.println(); + } + + private static void printResults(Options options, List phases, int batchSize, long rowsStored) { + List problems = new ArrayList<>(); + for (Phase phase : phases) { + if (phase.status() != 200) { + problems.add("FAILED. " + phase.title().split(":")[0] + " returned HTTP " + phase.status() + "."); + continue; + } + Recording recording = phase.recording(); + String what = phase.title().split(":")[0].toLowerCase(Locale.ROOT); + int selects = recording.roundTrips("select") - recording.roundTrips("select nextval"); + if (options.prices() && selects > 0) { + problems.add(number(selects) + " SELECTS. saveAll() looked up every price change before inserting it."); + } + if (recording.commits() > 1) { + problems.add(number(recording.commits()) + " COMMITS. Every row was its own transaction."); + } + int rowsWritten = phase.rowsWritten(); + if (recording.roundTrips() * 10L > rowsWritten) { + problems.add(number(recording.roundTrips()) + " ROUND TRIPS. The " + what + " wrote " + number(rowsWritten) + + " rows, " + perTrip(rowsWritten, recording.roundTrips()) + " per round trip."); + } + boolean importPhase = phase == phases.getFirst() && !options.prices() && options.jpa(); + if (importPhase && batchSize > 0 && phase.peakEntities() > 4 * batchSize) { + problems.add(number(phase.peakEntities()) + " ENTITIES IN MEMORY. The persistence context held the whole " + + what + " until it ended."); + } + } + if (problems.isEmpty()) { + Phase first = phases.getFirst(); + StringBuilder ok = new StringBuilder("RESULT: OK. " + number(rowsStored) + " rows in " + + roundTrips(first.recording().roundTrips())); + if (phases.size() > 1) { + ok.append(", updated in ").append(roundTrips(phases.get(1).recording().roundTrips())); + } + if (!options.prices() && options.jpa()) { + ok.append(", at most ").append(number(first.peakEntities())).append(" entities in memory"); + } + System.out.println(ok.append('.')); + } else { + problems.forEach(problem -> System.out.println("RESULT: " + problem)); + } + System.out.println(); + } + + private static String roundTrips(int count) { + return number(count) + (count == 1 ? " round trip" : " round trips"); + } + + private static String perTrip(int rows, int roundTrips) { + double average = roundTrips == 0 ? 0 : (double) rows / roundTrips; + return String.format(Locale.US, "%.1f", average); + } + + private static String clip(String sql) { + return sql.length() > WIDTH ? sql.substring(0, WIDTH - 3) + "..." : sql; + } + + static String number(long value) { + return String.format(Locale.US, "%,d", value); + } + + private static Options parse(String[] args) { + String strategy = "batched"; + int rows = 10_000; + boolean stock = false; + boolean prices = false; + Boolean rewrite = null; + boolean sql = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--strategy" -> { + strategy = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!STRATEGIES.contains(strategy)) { + throw new IllegalArgumentException("Unknown strategy '" + strategy + "'. Use one of: " + String.join(", ", STRATEGIES)); + } + } + case "--rows" -> rows = number(value(args, ++i, arg), arg, 1, 100_000); + case "--stock" -> stock = true; + case "--prices" -> prices = true; + case "--rewrite" -> { + String value = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!value.equals("on") && !value.equals("off")) { + throw new IllegalArgumentException("--rewrite must be on or off, got: " + value); + } + rewrite = value.equals("on"); + } + case "--sql" -> sql = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (stock && prices) { + throw new IllegalArgumentException("Use --stock or --prices, not both."); + } + if (stock && (strategy.equals("jdbc") || strategy.equals("copy"))) { + throw new IllegalArgumentException("--stock needs JPA: the " + strategy + " importer does not write stock levels (that is one of its trade-offs)."); + } + return new Options(strategy, rows, stock, prices, rewrite, 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.replace(",", "").replace("_", "")); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + number(max) + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --rows how many products the feed has (default: 10000)"); + System.out.println(" --strategy how they reach the database (default: batched)"); + System.out.println(" one-by-one JPA, one transaction per row (never changes: the reference)"); + System.out.println(" batched JPA, one transaction, saveAll (Tasks 2 to 6 change this)"); + System.out.println(" rewrite batched, with reWriteBatchedInserts=true for this run"); + System.out.println(" jdbc JdbcTemplate.batchUpdate, no entities (Task 8)"); + System.out.println(" copy Postgres COPY through the driver's CopyManager (Task 8)"); + System.out.println(" --rewrite on|off force reWriteBatchedInserts for this run (default: application.properties)"); + System.out.println(" --stock every product gets 3 stock levels, then a second feed updates them all"); + System.out.println(" --prices write the price history instead: ids are UUIDs made in Java"); + System.out.println(" --sql also list the first 25 round trips, in order"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --strategy rewrite"); + System.out.println(" ./demo --stock --rows 2000"); + System.out.println(" ./demo --prices --rows 1000"); + System.out.println(" ./demo --strategy copy --rows 100000"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java new file mode 100644 index 0000000..461ff10 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Feed.java @@ -0,0 +1,55 @@ +package com.amigoscode.batching.demo; + +import java.math.BigDecimal; +import java.util.List; + +/** Builds the supplier's CSV feed. Same input every time, so two runs can be compared. */ +final class Feed { + + static final List WAREHOUSES = List.of("GLA", "LON", "MAN"); + + private static final String[] COLOURS = {"Black", "White", "Red", "Blue", "Green", "Grey", "Yellow", "Navy"}; + private static final String[] THINGS = {"mug", "kettle", "lamp", "chair", "desk", "pillow", "towel", "teapot", "vase", "clock"}; + + private Feed() { + } + + /** The first feed: new products, optionally with stock in three warehouses. */ + static String products(int rows, boolean withStock) { + return build(rows, withStock, 0); + } + + /** The next day's feed: the same SKUs, every price up by 10% and different stock. */ + static String nextDay(int rows) { + return build(rows, true, 1); + } + + private static String build(int rows, boolean withStock, int day) { + StringBuilder csv = new StringBuilder(rows * 48); + csv.append("sku,name,price"); + if (withStock) { + WAREHOUSES.forEach(warehouse -> csv.append(',').append(warehouse)); + } + csv.append('\n'); + for (int i = 1; i <= rows; i++) { + BigDecimal price = BigDecimal.valueOf(100 + (i * 37L) % 9900, 2); + if (day > 0) { + price = price.multiply(new BigDecimal("1.10")).setScale(2, java.math.RoundingMode.HALF_UP); + } + csv.append(sku(i)).append(',') + .append(COLOURS[i % COLOURS.length]).append(' ').append(THINGS[i % THINGS.length]).append(" no. ").append(i) + .append(',').append(price.toPlainString()); + if (withStock) { + for (int w = 0; w < WAREHOUSES.size(); w++) { + csv.append(',').append((i * (w + 3) + day * 5) % 40); + } + } + csv.append('\n'); + } + return csv.toString(); + } + + static String sku(int i) { + return String.format("SKU-%06d", i); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java new file mode 100644 index 0000000..69cd8fa --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Inspect.java @@ -0,0 +1,149 @@ +package com.amigoscode.batching.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Shows what the database holds after a ./demo run: how each table gets its ids, the sequences and + * how far they have moved, how far apart the stored ids are, and every statement Postgres executed + * for the last request of the demo (pg_stat_statements). Run it with ./inspect (or .\inspect on + * Windows) after ./demo. + */ +public final class Inspect { + + private static final String ID_COLUMNS = """ + select c.table_name as "table", + c.data_type as "type", + case when c.is_identity = 'YES' then 'IDENTITY: Postgres makes it while it runs the INSERT' + when c.column_default like 'nextval%' then 'DEFAULT ' || c.column_default + else 'none: the application must send it' end as "where the id comes from" + from information_schema.columns c + where c.table_schema = current_schema() + and c.table_name in ('product', 'stock_level', 'price_change') + and c.column_name = 'id' + order by c.table_name + """; + + private static final String SEQUENCES = """ + select sequencename as "sequence", + increment_by as "increment by", + coalesce(last_value::text, '(never used)') as "last value handed out" + from pg_sequences + where schemaname = current_schema() + order by sequencename + """; + + private static final String IDS = """ + with ids as ( + select 'product' as t, null::text as uuid, id as n from product + union all select 'stock_level', null, id from stock_level + union all select 'price_change', id::text, null from price_change + ), + steps as ( + select t, n - lag(n) over (partition by t order by n) as step from ids where n is not null + ), + common as ( + select t, step, count(*) as times, + row_number() over (partition by t order by count(*) desc, step) as rank + from steps where step is not null group by t, step + ) + select tables.t as "table", + to_char(count(i.t), 'FM999,999,990') as "rows", + coalesce(min(i.n)::text, min(i.uuid), '') as "lowest id", + coalesce(max(i.n)::text, max(i.uuid), '') as "highest id", + coalesce((select string_agg('+' || c.step || ' (' || to_char(c.times, 'FM999,999,990') || 'x)', ', ' order by c.rank) + from common c where c.t = tables.t and c.rank <= 3), '') as "most common gaps between neighbouring ids" + from (values ('product'), ('stock_level'), ('price_change')) as tables (t) + left join ids i on i.t = tables.t + group by tables.t + order by tables.t + """; + + 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("Run it after ./demo. It reads the database only, and changes nothing."); + return; + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + if (!tablesExist(connection)) { + System.out.println(); + System.out.println("The tables do not exist yet. Run ./demo first."); + System.out.println(); + return; + } + System.out.println(); + System.out.println("WHERE EACH TABLE GETS ITS IDS (information_schema.columns)"); + printTable(connection, ID_COLUMNS); + System.out.println(); + System.out.println("SEQUENCES (pg_sequences)"); + if (printTable(connection, SEQUENCES) == 0) { + System.out.println(" none."); + } + System.out.println(); + System.out.println("THE ROWS AND THEIR IDS"); + printTable(connection, IDS); + System.out.println(); + System.out.println("WHAT POSTGRES EXECUTED FOR THE LAST REQUEST OF ./demo (pg_stat_statements)"); + if (!ServerStats.available(connection)) { + System.out.println(" pg_stat_statements is not loaded in this Postgres. The compose.yaml of this project loads it:"); + System.out.println(" docker compose down, then docker compose up -d."); + } else { + List rows = new ArrayList<>(); + rows.add(new String[] {"executions", "rows", "rows each", "statement"}); + for (ServerStats.Executed statement : ServerStats.read(connection)) { + long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls(); + String query = ServerStats.shorten(statement.query()); + rows.add(new String[] {Demo.number(statement.calls()), Demo.number(statement.rows()), Demo.number(each), + query.length() > 90 ? query.substring(0, 87) + "..." : query}); + } + Table.print(rows, 0, 1, 2); + } + System.out.println(); + } + } + + private static boolean tablesExist(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("select to_regclass('product') is not null")) { + result.next(); + return result.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) { + Table.print(rows); + } + return rows.size() - 1; + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java new file mode 100644 index 0000000..e5ed34b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/ServerStats.java @@ -0,0 +1,72 @@ +package com.amigoscode.batching.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads pg_stat_statements: what Postgres itself executed, counted on the server. The application + * side (SqlRecorder) counts round trips; this side counts statements. They are not the same number + * once the driver starts rewriting batches. + */ +final class ServerStats { + + /** One statement as Postgres normalised it ($1, $2 for the values), how often it ran, and the rows. */ + record Executed(String query, long calls, long rows) { + } + + private static final String READ = """ + select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows + from pg_stat_statements + where dbid = (select oid from pg_database where datname = current_database()) + and query !~* 'pg_stat_statements|pg_catalog|information_schema|pg_sequences|pg_class|pg_attribute' + and query ~* '^\\s*(insert|update|delete|select|copy|with)' + order by calls desc, query + """; + + private ServerStats() { + } + + /** False when the extension is not loaded (compose.yaml loads it; another Postgres may not). */ + static boolean available(Connection connection) { + try (Statement statement = connection.createStatement()) { + statement.execute("select 1 from pg_stat_statements limit 1"); + return true; + } catch (SQLException e) { + return false; + } + } + + static void reset(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("select pg_stat_statements_reset()"); + } + } + + static List read(Connection connection) throws SQLException { + List executed = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(READ)) { + while (result.next()) { + executed.add(new Executed(result.getString(1), result.getLong(2), result.getLong(3))); + } + } + return executed; + } + + /** A multi-row INSERT has one "($1,$2,$3)" per row: keeps the first one and replaces the rest with "...". */ + static String shorten(String query) { + int values = query.toLowerCase().indexOf(" values ("); + if (values < 0) { + return query; + } + int firstEnd = query.indexOf(')', values); + int rest = query.indexOf("),(", values); + if (rest < 0) { + rest = query.indexOf("), (", values); + } + return rest < 0 || rest != firstEnd ? query : query.substring(0, firstEnd + 1) + ",..."; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java new file mode 100644 index 0000000..15e2cda --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/demo/Table.java @@ -0,0 +1,41 @@ +package com.amigoscode.batching.demo; + +import java.util.Arrays; +import java.util.List; + +/** Prints rows as a plain text table. The first row is the header. */ +final class Table { + + private Table() { + } + + /** {@code rightAligned} are the column numbers to align to the right (the numbers). */ + static void print(List rows, int... rightAligned) { + if (rows.size() == 1) { + System.out.println(" (nothing)"); + return; + } + int[] widths = new int[rows.getFirst().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++) { + int column = c; + boolean right = r > 0 && Arrays.stream(rightAligned).anyMatch(n -> n == column); + line.append(String.format("%" + (right ? "" : "-") + 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()); + } + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java new file mode 100644 index 0000000..c75efc6 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/BadCsvException.java @@ -0,0 +1,16 @@ +package com.amigoscode.batching.imports; + +/** A line of the uploaded CSV that cannot be read. Becomes a 400 with the line number. */ +public class BadCsvException extends RuntimeException { + + private final int line; + + public BadCsvException(int line, String problem) { + super("Line " + line + ": " + problem); + this.line = line; + } + + public int line() { + return line; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java new file mode 100644 index 0000000..c4c3599 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportController.java @@ -0,0 +1,47 @@ +package com.amigoscode.batching.imports; + +import java.io.Reader; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * The supplier's feed arrives as CSV in the request body (see ProductCsv for the format). + * + *

+ * POST /api/imports/products?strategy=batched   new products: one-by-one | batched | jdbc | copy
+ * PUT  /api/imports/products                    same SKUs again: new prices and new stock
+ * POST /api/imports/prices                      one price change per row, into the price history
+ * 
+ */ +@RestController +@RequestMapping("/api/imports") +public class ImportController { + + public record ImportResponse(String strategy, long rows) { + } + + private final ImportService imports; + + public ImportController(ImportService imports) { + this.imports = imports; + } + + @PostMapping(path = "/products", consumes = "text/csv") + public ImportResponse importProducts(@RequestParam(defaultValue = "batched") String strategy, Reader body) { + ImportStrategy chosen = ImportStrategy.from(strategy); + return new ImportResponse(chosen.label(), imports.importProducts(chosen, ProductCsv.read(body))); + } + + @PutMapping(path = "/products", consumes = "text/csv") + public ImportResponse updateProducts(Reader body) { + return new ImportResponse("update", imports.updateProducts(ProductCsv.read(body).toList())); + } + + @PostMapping(path = "/prices", consumes = "text/csv") + public ImportResponse recordPrices(Reader body) { + return new ImportResponse("price-history", imports.recordPrices(ProductCsv.read(body).toList())); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java new file mode 100644 index 0000000..a3276d9 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportService.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.imports; + +import com.amigoscode.batching.price.PriceHistory; +import com.amigoscode.batching.product.JdbcProductImporter; +import com.amigoscode.batching.product.ProductImporter; +import com.amigoscode.batching.product.ProductRow; +import java.util.List; +import org.springframework.stereotype.Service; + +/** Picks the importer. Deliberately not transactional: each importer decides its own transactions. */ +@Service +public class ImportService { + + private final ProductImporter jpa; + private final JdbcProductImporter jdbc; + private final PriceHistory priceHistory; + + public ImportService(ProductImporter jpa, JdbcProductImporter jdbc, PriceHistory priceHistory) { + this.jpa = jpa; + this.jdbc = jdbc; + this.priceHistory = priceHistory; + } + + public long importProducts(ImportStrategy strategy, Iterable rows) { + return switch (strategy) { + case ONE_BY_ONE -> jpa.importOneByOne(rows); + case BATCHED -> jpa.importBatched(rows); + case JDBC -> jdbc.batchInsert(rows); + case COPY -> jdbc.copy(rows); + }; + } + + public long updateProducts(List rows) { + return jpa.updateAll(rows); + } + + public long recordPrices(List rows) { + return priceHistory.record(rows); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java new file mode 100644 index 0000000..905bca8 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.imports; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** How the rows of an import reach the database. Chosen per request with ?strategy=. */ +public enum ImportStrategy { + + /** JPA, one transaction per row. Stays as it is, so you can always compare against it. */ + ONE_BY_ONE, + /** JPA, the whole file in one transaction with saveAll. Tasks 2 to 6. */ + BATCHED, + /** JdbcTemplate.batchUpdate, no entities. Task 8. */ + JDBC, + /** Postgres COPY through the driver's CopyManager. Task 8. */ + COPY; + + public String label() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + public static ImportStrategy from(String value) { + return Arrays.stream(values()) + .filter(strategy -> strategy.label().equals(value == null ? "" : value.trim().toLowerCase(Locale.ROOT))) + .findFirst() + .orElseThrow(() -> new UnknownStrategyException(value)); + } + + public static String labels() { + return Arrays.stream(values()).map(ImportStrategy::label).collect(Collectors.joining(", ")); + } + + public static class UnknownStrategyException extends RuntimeException { + + public UnknownStrategyException(String value) { + super("Unknown strategy '" + value + "'. Use one of: " + labels()); + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java new file mode 100644 index 0000000..21dbd43 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/imports/ProductCsv.java @@ -0,0 +1,184 @@ +package com.amigoscode.batching.imports; + +import com.amigoscode.batching.product.ProductRow; +import java.io.IOException; +import java.io.Reader; +import java.io.UncheckedIOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/** + * Reads a product feed one row at a time, so a big file is never held in memory as a whole. + * + *
+ * sku,name,price,LON,MAN
+ * SKU-00001,"Mug, large",7.50,12,3
+ * 
+ * + * The first three columns are fixed. Every column after them is a warehouse, and its value is the + * stock in that warehouse. Fields may be quoted with double quotes, and a quote inside a quoted + * field is written twice (""). + */ +public final class ProductCsv implements Iterable { + + private final Reader reader; + private boolean used; + + private ProductCsv(Reader reader) { + this.reader = reader; + } + + public static ProductCsv read(Reader reader) { + return new ProductCsv(reader); + } + + /** Can be iterated once: the rows are read from the reader as you go. */ + @Override + public Iterator iterator() { + if (used) { + throw new IllegalStateException("A ProductCsv can only be read once"); + } + used = true; + Records records = new Records(reader); + List header = records.next(); + if (header == null || header.size() < 3 + || !header.get(0).equals("sku") || !header.get(1).equals("name") || !header.get(2).equals("price")) { + throw new BadCsvException(1, "the first line must be the header sku,name,price followed by optional warehouse codes"); + } + List warehouses = List.copyOf(header.subList(3, header.size())); + return new Iterator<>() { + + private List next = records.next(); + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public ProductRow next() { + if (next == null) { + throw new NoSuchElementException(); + } + ProductRow row = toRow(next, records.line(), header.size(), warehouses); + next = records.next(); + return row; + } + }; + } + + /** Reads the whole file into a list. Fine for a small file, or when you need every row at once. */ + public List toList() { + List rows = new ArrayList<>(); + forEach(rows::add); + return rows; + } + + private static ProductRow toRow(List fields, int line, int columns, List warehouses) { + if (fields.size() != columns) { + throw new BadCsvException(line, "expected " + columns + " fields, found " + fields.size()); + } + if (fields.get(0).isBlank()) { + throw new BadCsvException(line, "sku is empty"); + } + BigDecimal price; + try { + price = new BigDecimal(fields.get(2).trim()); + } catch (NumberFormatException e) { + throw new BadCsvException(line, "price is not a number: " + fields.get(2)); + } + Map stock = new LinkedHashMap<>(); + for (int i = 0; i < warehouses.size(); i++) { + String value = fields.get(3 + i).trim(); + try { + stock.put(warehouses.get(i), Integer.parseInt(value)); + } catch (NumberFormatException e) { + throw new BadCsvException(line, "stock for " + warehouses.get(i) + " is not a whole number: " + value); + } + } + return new ProductRow(fields.get(0).trim(), fields.get(1), price, stock); + } + + /** Splits the text into records of fields. Knows about quotes, nothing else. */ + private static final class Records { + + private final Reader reader; + private int linesRead; + private int recordStart; + + Records(Reader reader) { + this.reader = reader; + } + + /** The line the last record started on. */ + int line() { + return recordStart; + } + + /** The next record, or null at the end of the file. Empty lines are skipped. */ + List next() { + int c = read(); + while (c == '\n' || c == '\r') { + if (c == '\n') { + linesRead++; + } + c = read(); + } + if (c == -1) { + return null; + } + recordStart = linesRead + 1; + List fields = new ArrayList<>(); + StringBuilder field = new StringBuilder(); + boolean quoted = false; + while (true) { + if (quoted) { + if (c == -1) { + throw new BadCsvException(recordStart, "a quoted field is never closed"); + } + if (c == '"') { + int after = read(); + if (after != '"') { + quoted = false; + c = after; + continue; + } + field.append('"'); + } else { + if (c == '\n') { + linesRead++; + } + field.append((char) c); + } + } else if (c == '"' && field.isEmpty()) { + quoted = true; + } else if (c == ',') { + fields.add(field.toString()); + field.setLength(0); + } else if (c == '\n' || c == -1) { + if (c == '\n') { + linesRead++; + } + fields.add(field.toString()); + return fields; + } else if (c != '\r') { + field.append((char) c); + } + c = read(); + } + } + + private int read() { + try { + return reader.read(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java new file mode 100644 index 0000000..f152c58 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChange.java @@ -0,0 +1,80 @@ +package com.amigoscode.batching.price; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.PostLoad; +import jakarta.persistence.PostPersist; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; +import org.springframework.data.domain.Persistable; + +/** + * One line of the price history. The id is a UUID made in Java, so the database is not asked for + * one. + * + *

Spring Data's save() decides between persist (INSERT) and merge (SELECT, then INSERT or + * UPDATE) by asking isNew(). By default "new" means "the id is null", and this id is never null. + * Implementing Persistable answers the question properly: new until it has been saved or loaded. + */ +@Entity +@Table(name = "price_change") +public class PriceChange implements Persistable { + + @Id + private UUID id; + + private String sku; + + private BigDecimal price; + + private Instant changedAt; + + @Transient + private boolean isNew = true; + + protected PriceChange() { + } + + public PriceChange(String sku, BigDecimal price, Instant changedAt) { + this.id = UUID.randomUUID(); + this.sku = sku; + this.price = price; + this.changedAt = changedAt; + } + + @Override + public UUID getId() { + return id; + } + + @Override + public boolean isNew() { + return isNew; + } + + /** Once it is in the database, the next save() must be a merge (an UPDATE), not a second INSERT. */ + @PostPersist + @PostLoad + void markNotNew() { + isNew = false; + } + + public String getSku() { + return sku; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public Instant getChangedAt() { + return changedAt; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java new file mode 100644 index 0000000..aa3701b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java @@ -0,0 +1,7 @@ +package com.amigoscode.batching.price; + +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PriceChangeRepository extends JpaRepository { +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java new file mode 100644 index 0000000..c979835 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/price/PriceHistory.java @@ -0,0 +1,28 @@ +package com.amigoscode.batching.price; + +import com.amigoscode.batching.product.ProductRow; +import java.time.Instant; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Writes one price change per row of the feed, all in one transaction. */ +@Service +public class PriceHistory { + + private final PriceChangeRepository priceChanges; + + public PriceHistory(PriceChangeRepository priceChanges) { + this.priceChanges = priceChanges; + } + + @Transactional + public int record(List rows) { + Instant now = Instant.now(); + List changes = rows.stream() + .map(row -> new PriceChange(row.sku(), row.price(), now)) + .toList(); + priceChanges.saveAll(changes); + return changes.size(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java new file mode 100644 index 0000000..fa28d92 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java @@ -0,0 +1,96 @@ +package com.amigoscode.batching.product; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.postgresql.PGConnection; +import org.postgresql.copy.CopyIn; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Imports products without JPA: no entities, no persistence context, no cascades. The id comes from + * the column's default (nextval of the sequence), and stock levels are not imported at all. + */ +@Service +public class JdbcProductImporter { + + private static final String INSERT = "insert into product (sku, name, price) values (?, ?, ?)"; + private static final String COPY = "copy product (sku, name, price) from stdin with (format csv)"; + + private final JdbcTemplate jdbc; + private final int batchSize; + + public JdbcProductImporter(JdbcTemplate jdbc, + @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) { + this.jdbc = jdbc; + this.batchSize = batchSize; + } + + /** JdbcTemplate.batchUpdate: one round trip per batchSize rows, in one transaction. */ + @Transactional + public int batchInsert(Iterable rows) { + List chunk = new ArrayList<>(batchSize); + int count = 0; + for (ProductRow row : rows) { + chunk.add(row); + count++; + if (chunk.size() == batchSize) { + insert(chunk); + } + } + insert(chunk); + return count; + } + + private void insert(List chunk) { + if (chunk.isEmpty()) { + return; + } + jdbc.batchUpdate(INSERT, chunk, chunk.size(), (statement, row) -> { + statement.setString(1, row.sku()); + statement.setString(2, row.name()); + statement.setBigDecimal(3, row.price()); + }); + chunk.clear(); + } + + /** + * COPY: one statement, and the rows stream after it as CSV text. Every text field is quoted and + * every quote inside it doubled, so commas, quotes and line breaks in a name arrive unchanged. + */ + @Transactional + public long copy(Iterable rows) { + return jdbc.execute((ConnectionCallback) connection -> { + CopyIn copy = connection.unwrap(PGConnection.class).getCopyAPI().copyIn(COPY); + try { + for (ProductRow row : rows) { + byte[] line = (csv(row.sku()) + "," + csv(row.name()) + "," + row.price().toPlainString() + "\n") + .getBytes(StandardCharsets.UTF_8); + copy.writeToCopy(line, 0, line.length); + } + return copy.endCopy(); + } finally { + if (copy.isActive()) { + cancel(copy); + } + } + }); + } + + private static String csv(String value) { + return "\"" + value.replace("\"", "\"\"") + "\""; + } + + private static void cancel(CopyIn copy) { + try { + copy.cancelCopy(); + } catch (SQLException ignored) { + // The COPY already failed. That first error is the one worth reporting. + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java new file mode 100644 index 0000000..256310b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/Product.java @@ -0,0 +1,91 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +@Entity +@Table(name = "product") +public class Product { + + /** + * The id comes from product_seq. Hibernate asks the sequence for a value once and then hands + * out 50 ids from memory, so it knows every id before it sends a single INSERT, and can send the + * INSERTs in batches. allocationSize must be the same number as the sequence's INCREMENT BY. + */ + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_ids") + @SequenceGenerator(name = "product_ids", sequenceName = "product_seq", allocationSize = 50) + private Long id; + + private String sku; + + private String name; + + private BigDecimal price; + + @OneToMany(mappedBy = "product", cascade = CascadeType.ALL) + private List stockLevels = new ArrayList<>(); + + protected Product() { + } + + public Product(String sku, String name, BigDecimal price) { + this.sku = sku; + this.name = name; + this.price = price; + } + + /** A new product with one stock level per warehouse in the row. */ + public static Product from(ProductRow row) { + Product product = new Product(row.sku(), row.name(), row.price()); + new TreeMap<>(row.stock()).forEach(product::addStock); + return product; + } + + public void addStock(String warehouse, int quantity) { + stockLevels.add(new StockLevel(this, warehouse, quantity)); + } + + /** Takes the new price and the new stock per warehouse from the feed. */ + public void update(ProductRow row) { + this.price = row.price(); + Map stock = row.stock(); + for (StockLevel level : stockLevels) { + Integer quantity = stock.get(level.getWarehouse()); + if (quantity != null) { + level.setQuantity(quantity); + } + } + } + + public Long getId() { + return id; + } + + public String getSku() { + return sku; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public List getStockLevels() { + return stockLevels; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java new file mode 100644 index 0000000..7f62764 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductImporter.java @@ -0,0 +1,88 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Imports the supplier's feed with JPA. */ +@Service +public class ProductImporter { + + /** Postgres accepts at most 32,767 bind parameters in one statement, so a long IN list is split. */ + private static final int SKUS_PER_QUERY = 1_000; + + private final ProductRepository products; + private final EntityManager entityManager; + private final int batchSize; + + public ProductImporter(ProductRepository products, EntityManager entityManager, + @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) { + this.products = products; + this.entityManager = entityManager; + this.batchSize = batchSize; + } + + /** + * The reference. Not @Transactional, so every save() is its own transaction: one INSERT and one + * COMMIT per row. Leave this one as it is, so you can always compare against it. + */ + public int importOneByOne(Iterable rows) { + int count = 0; + for (ProductRow row : rows) { + products.save(Product.from(row)); + count++; + } + return count; + } + + /** + * The whole file in one transaction. Every batchSize products the persistence context is flushed + * (the INSERTs are sent, as one JDBC batch) and cleared (Hibernate forgets those entities), so + * memory stays flat however big the file is. Still one transaction: flush is not commit. + */ + @Transactional + public int importBatched(Iterable rows) { + List chunk = new ArrayList<>(batchSize); + int count = 0; + for (ProductRow row : rows) { + chunk.add(Product.from(row)); + count++; + if (chunk.size() == batchSize) { + saveAndForget(chunk); + } + } + saveAndForget(chunk); + return count; + } + + private void saveAndForget(List chunk) { + products.saveAll(chunk); + entityManager.flush(); + entityManager.clear(); + chunk.clear(); + } + + /** The next day's feed: same SKUs, new prices and new stock. Returns how many products changed. */ + @Transactional + public int updateAll(List rows) { + Map bySku = new LinkedHashMap<>(); + rows.forEach(row -> bySku.put(row.sku(), row)); + List skus = new ArrayList<>(bySku.keySet()); + int updated = 0; + for (int from = 0; from < skus.size(); from += SKUS_PER_QUERY) { + List page = skus.subList(from, Math.min(from + SKUS_PER_QUERY, skus.size())); + for (Product product : products.findWithStockLevelsBySkuIn(page)) { + product.update(bySku.get(product.getSku())); + updated++; + } + } + // No save() needed: every product is managed, so Hibernate sends an UPDATE for each one it + // finds changed when the transaction commits. + return updated; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java new file mode 100644 index 0000000..abb1615 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRepository.java @@ -0,0 +1,13 @@ +package com.amigoscode.batching.product; + +import java.util.Collection; +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 ProductRepository extends JpaRepository { + + @Query("select distinct p from Product p left join fetch p.stockLevels where p.sku in :skus") + List findWithStockLevelsBySkuIn(@Param("skus") Collection skus); +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java new file mode 100644 index 0000000..b936374 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/ProductRow.java @@ -0,0 +1,16 @@ +package com.amigoscode.batching.product; + +import java.math.BigDecimal; +import java.util.Map; + +/** One line of the supplier's feed. {@code stock} is the quantity per warehouse code, and may be empty. */ +public record ProductRow(String sku, String name, BigDecimal price, Map stock) { + + public ProductRow { + stock = Map.copyOf(stock); + } + + public ProductRow(String sku, String name, BigDecimal price) { + this(sku, name, price, Map.of()); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java new file mode 100644 index 0000000..95579ea --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/java/com/amigoscode/batching/product/StockLevel.java @@ -0,0 +1,55 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; + +/** How many of a product one warehouse holds. Saved together with its product (cascade). */ +@Entity +@Table(name = "stock_level") +public class StockLevel { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "stock_level_ids") + @SequenceGenerator(name = "stock_level_ids", sequenceName = "stock_level_seq", allocationSize = 50) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id") + private Product product; + + private String warehouse; + + private int quantity; + + protected StockLevel() { + } + + StockLevel(Product product, String warehouse, int quantity) { + this.product = product; + this.warehouse = warehouse; + this.quantity = quantity; + } + + public Long getId() { + return id; + } + + public String getWarehouse() { + return warehouse; + } + + public int getQuantity() { + return quantity; + } + + void setQuantity(int quantity) { + this.quantity = quantity; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties new file mode 100644 index 0000000..4453833 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=batch-writes + +# Postgres from compose.yaml. Port 5455 so it does not clash with a Postgres you already run. +# Task 4: reWriteBatchedInserts=true makes the Postgres driver turn a batch of INSERTs into +# multi-row INSERT statements. (A DB_URL environment variable replaces this whole URL, option included.) +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5455/batching?reWriteBatchedInserts=true} +spring.datasource.username=${DB_USER:batching} +spring.datasource.password=${DB_PASSWORD:batching} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# schema.sql drops and creates the tables on every start, so every run begins empty. +spring.sql.init.mode=always + +# Send INSERTs and UPDATEs in JDBC batches of 50 statements. +spring.jpa.properties.hibernate.jdbc.batch_size=50 + +# Task 5: sort the INSERTs and UPDATEs of a flush by table, so products and stock levels do not +# take turns and break every batch. +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true + +# Counts the entities in the persistence context at every flush. ./demo and the tests read it. +spring.jpa.properties.hibernate.session_factory.interceptor=com.amigoscode.batching.db.ManagedEntities + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..b96d81c --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/main/resources/schema.sql @@ -0,0 +1,37 @@ +-- Runs on every start, so every run begins with empty tables. + +-- Counts every statement Postgres executes. ./demo and ./inspect read it. It needs +-- shared_preload_libraries=pg_stat_statements, which compose.yaml sets. +create extension if not exists pg_stat_statements; + +drop table if exists stock_level, product, price_change; +drop sequence if exists product_seq, stock_level_seq; + +-- Ids come from sequences that move 50 at a time. Hibernate asks once and uses the 50 values in +-- memory, so allocationSize = 50 in Product and StockLevel must match INCREMENT BY 50 here. +create sequence product_seq increment by 50; +create sequence stock_level_seq increment by 50; + +create table product ( + id bigint primary key default nextval('product_seq'), + sku text not null unique, + name text not null, + price numeric(10,2) not null check (price >= 0) +); + +create table stock_level ( + id bigint primary key default nextval('stock_level_seq'), + product_id bigint not null references product (id), + warehouse text not null, + quantity int not null check (quantity >= 0) +); + +create index stock_level_product_id on stock_level (product_id); + +-- The id is a UUID made in Java (see PriceChange). +create table price_change ( + id uuid primary key, + sku text not null, + price numeric(10,2) not null, + changed_at timestamptz not null +); diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java new file mode 100644 index 0000000..50781ec --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.batching; + +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. Task 3 is an inspection task: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the CSV format and the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See 10,000 round trips"); + TASKS.put("2", "Task 2: Let Hibernate batch: SEQUENCE instead of IDENTITY"); + TASKS.put("4", "Task 4: Multi-row INSERTs: reWriteBatchedInserts"); + TASKS.put("5", "Task 5: Parents and children: order_inserts and order_updates"); + TASKS.put("6", "Task 6: Flat memory: flush and clear"); + TASKS.put("7", "Task 7: Ids made in Java: no SELECT before every INSERT"); + TASKS.put("8", "Task 8: Leave JPA: JdbcTemplate and COPY"); + } + + 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/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java new file mode 100644 index 0000000..6dca681 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ImportControllerTest.java @@ -0,0 +1,95 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.batching.imports.ImportController; +import com.amigoscode.batching.imports.ImportService; +import com.amigoscode.batching.imports.ImportStrategy; +import com.amigoscode.batching.product.ProductRow; +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; +import org.springframework.dao.DataIntegrityViolationException; +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, ImportService is a stub. They + * pass from the start and must keep passing whatever you change behind the controller. + */ +@Tag("baseline") +class ImportControllerTest { + + private static final String CSV = "sku,name,price\nSKU-1,Mug,7.50\nSKU-2,Kettle,24.00\n"; + + @Test + @DisplayName("HTTP: POST /api/imports/products reads the CSV row by row and returns how many rows were imported") + void importReturnsTheRowCount() throws Exception { + List received = new ArrayList<>(); + ImportStrategy[] strategy = new ImportStrategy[1]; + + api((chosen, rows) -> { + strategy[0] = chosen; + rows.forEach(received::add); + return received.size(); + }).perform(post("/api/imports/products?strategy=copy").contentType("text/csv").content(CSV)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.strategy").value("copy")) + .andExpect(jsonPath("$.rows").value(2)); + + assertThat(strategy[0]).isEqualTo(ImportStrategy.COPY); + assertThat(received).extracting(ProductRow::sku).containsExactly("SKU-1", "SKU-2"); + } + + @Test + @DisplayName("HTTP: an unknown strategy returns 400 UNKNOWN_STRATEGY") + void unknownStrategy() throws Exception { + api((chosen, rows) -> 0).perform(post("/api/imports/products?strategy=faster").contentType("text/csv").content(CSV)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("UNKNOWN_STRATEGY")); + } + + @Test + @DisplayName("HTTP: a row that cannot be read returns 400 BAD_CSV with its line number") + void badRow() throws Exception { + api((chosen, rows) -> { + rows.forEach(row -> { }); + return 0; + }).perform(post("/api/imports/products").contentType("text/csv").content(CSV + "SKU-3,Lamp,cheap\n")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("BAD_CSV")) + .andExpect(jsonPath("$.line").value(4)); + } + + @Test + @DisplayName("HTTP: a row the database refuses returns 422 IMPORT_REJECTED") + void rejectedRow() throws Exception { + api((chosen, rows) -> { + throw new DataIntegrityViolationException("new row violates check constraint \"product_price_check\""); + }).perform(post("/api/imports/products").contentType("text/csv").content(CSV)) + .andExpect(status().isUnprocessableContent()) + .andExpect(jsonPath("$.code").value("IMPORT_REJECTED")); + } + + private interface Importer { + long run(ImportStrategy strategy, Iterable rows); + } + + /** The controller wired to an ImportService whose importProducts does whatever the test says. */ + private static MockMvc api(Importer importer) { + ImportService stub = new ImportService(null, null, null) { + @Override + public long importProducts(ImportStrategy strategy, Iterable rows) { + return importer.run(strategy, rows); + } + }; + return MockMvcBuilders.standaloneSetup(new ImportController(stub)) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java new file mode 100644 index 0000000..ae14e93 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/JdbcImportIT.java @@ -0,0 +1,88 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlCall; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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; + +/** No JPA: JdbcTemplate.batchUpdate and Postgres COPY. */ +@Tag("task8") +class JdbcImportIT extends IntegrationTest { + + /** A comma, double quotes, a backslash, a line break and a tab: everything that breaks hand-made CSV. */ + private static final String AWKWARD_NAME = "Mug, \"large\"\\0.5 l\nsecond line\tand a tab"; + + @Test + @DisplayName("JdbcTemplate: 2,000 products in 40 round trips, batches of 50") + void jdbcTemplateSendsBatches() { + Recording recording = record(() -> jdbcImporter.batchInsert(Rows.products(2_000))); + + assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("JdbcTemplate: a name with commas, quotes, a backslash and a line break is stored exactly as sent") + void jdbcTemplateStoresAwkwardNames() { + jdbcImporter.batchInsert(List.of(new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")))); + + assertThat(jdbc.queryForObject("select name from product", String.class)).isEqualTo(AWKWARD_NAME); + } + + @Test + @DisplayName("COPY: 2,000 products in one statement") + void copyIsOneStatement() { + Recording recording = record(() -> jdbcImporter.copy(Rows.products(2_000))); + + assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(1); + assertThat(recording.calls().getFirst().kind()).as("kind of round trip").isEqualTo(SqlCall.Kind.COPY); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent") + void copyStoresAwkwardNames() { + List rows = List.of( + new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")), + new ProductRow("SKU-2", "Plain name", new BigDecimal("1.00"))); + + try { + jdbcImporter.copy(rows); + } catch (RuntimeException e) { + throw new AssertionError("COPY refused the rows: " + rootMessage(e), e); + } + + assertThat(jdbc.queryForList("select name from product order by sku", String.class)) + .containsExactly(AWKWARD_NAME, "Plain name"); + } + + @Test + @DisplayName("COPY: one bad row (a negative price) and nothing is stored, not even the rows before it") + void oneBadRowStopsTheWholeCopy() { + List rows = new ArrayList<>(Rows.products(2_000)); + rows.set(1_500, new ProductRow("SKU-1501", "Product 1501", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> jdbcImporter.copy(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products stored").isZero(); + } + + private static String rootMessage(Throwable e) { + Throwable root = e; + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + } + return root.getMessage(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java new file mode 100644 index 0000000..ad70242 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/OneByOneIT.java @@ -0,0 +1,42 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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 1. These tests pass on purpose: they pin down the problem so you can see what the fixes change. */ +@Tag("task1") +class OneByOneIT extends IntegrationTest { + + @Test + @DisplayName("One by one: 500 rows are 500 INSERTs, each in its own round trip and its own transaction (this documents the problem)") + void everyRowIsItsOwnRoundTripAndTransaction() { + Recording recording = record(() -> productImporter.importOneByOne(Rows.products(500))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(500); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(1); + assertThat(recording.commits()).as("commits").isEqualTo(500); + assertThat(count("product")).as("products stored").isEqualTo(500); + } + + @Test + @DisplayName("One by one: a bad row in the middle leaves every row before it in the database (this documents the problem)") + void aBadRowLeavesHalfAnImport() { + List rows = new ArrayList<>(Rows.products(100)); + rows.set(60, new ProductRow("SKU-61", "Product 61", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> productImporter.importOneByOne(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products left behind by a failed import").isEqualTo(60); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java new file mode 100644 index 0000000..cee1bca --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java @@ -0,0 +1,68 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** 500 products with 3 stock levels each: 500 parents and 1,500 children saved in one go. */ +@Tag("task5") +class ParentsAndChildrenIT extends IntegrationTest { + + @Test + @DisplayName("Insert: 500 products and 1,500 stock levels go in full batches: 10 product batches and 30 stock level batches") + void insertsAreSortedIntoFullBatches() { + Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + String sent = "\n" + recording.describe(); + assertThat(recording.roundTrips("insert into product")).as("product INSERT round trips" + sent).isLessThanOrEqualTo(10); + assertThat(recording.roundTrips("insert into stock_level")).as("stock level INSERT round trips" + sent).isLessThanOrEqualTo(30); + } + + @Test + @DisplayName("Insert: stock levels get their ids from a sequence too, at most 31 nextval calls for 1,500 of them") + void stockLevelIdsComeFromASequence() { + Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + assertThat(recording.roundTrips("select nextval('stock_level_seq')")) + .as("nextval('stock_level_seq') round trips\n" + recording.describe()).isBetween(1, 31); + } + + @Test + @DisplayName("Update: a new price and new stock for 500 products takes at most 40 UPDATE round trips, not 1,000") + void updatesAreSortedIntoFullBatches() { + productImporter.importBatched(Rows.productsWithStock(500, 0)); + + Recording recording = record(() -> productImporter.updateAll(Rows.productsWithStock(500, 1))); + + assertThat(recording.roundTrips("update")).as("UPDATE round trips\n" + recording.describe()).isLessThanOrEqualTo(40); + assertThat(stockLevelsMatching(1)).as("stock levels that now hold the next day's quantity").isEqualTo(1_500); + // Every price went up by 1.00: 1.01 + ... + 6.00 is 1,752.50, plus 500 x 1.00. + assertThat(jdbc.queryForObject("select sum(price) from product", java.math.BigDecimal.class)) + .as("sum of the new prices").isEqualByComparingTo("2252.50"); + } + + @Test + @DisplayName("Insert: every stock level is stored and points to its own product") + void everyStockLevelBelongsToItsProduct() { + productImporter.importBatched(Rows.productsWithStock(500, 0)); + + assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500); + assertThat(stockLevelsMatching(0)).as("stock levels whose quantity matches their own product's row").isEqualTo(1_500); + } + + /** Stock levels whose quantity is what Rows.productsWithStock(.., day) gave their product. */ + private long stockLevelsMatching(int day) { + return jdbc.queryForObject(""" + select count(*) + from stock_level s + join product p on p.id = s.product_id + where s.quantity = (cast(substring(p.sku from 5) as int) + + ? * case s.warehouse when 'GLA' then 1 when 'LON' then 2 else 3 end) % 10 + """, Long.class, day); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java new file mode 100644 index 0000000..65f3115 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PersistenceContextIT.java @@ -0,0 +1,63 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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; + +/** + * ManagedEntities counts the entities in the persistence context every time Hibernate flushes. + * Every managed entity stays in memory, with a copy of its values for dirty checking, until the + * transaction ends or the persistence context is cleared. + */ +@Tag("task6") +class PersistenceContextIT extends IntegrationTest { + + @Test + @DisplayName("Memory: importing 2,000 products never holds more than 50 entities in the persistence context") + void productsAreNotKeptInMemory() { + record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("Memory: with stock levels, never more than 200 entities (50 products and their 150 stock levels)") + void productsWithStockAreNotKeptInMemory() { + record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(200); + assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500); + } + + @Test + @DisplayName("Memory: clearing every 50 rows keeps the batches full: still 40 INSERT batches of 50 for 2,000 products") + void clearingKeepsTheBatchesFull() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + } + + @Test + @DisplayName("Memory: flush is not commit: a bad row near the end still rolls back the whole import") + void flushIsNotCommit() { + List rows = new ArrayList<>(Rows.products(2_000)); + rows.set(1_900, new ProductRow("SKU-1901", "Product 1901", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> productImporter.importBatched(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products left behind by a failed import").isZero(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java new file mode 100644 index 0000000..82a6e87 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/PriceHistoryIT.java @@ -0,0 +1,64 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.price.PriceChange; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +import java.time.Instant; +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.beans.factory.annotation.Autowired; +import org.springframework.transaction.support.TransactionTemplate; + +/** PriceChange ids are UUIDs made in Java, so the id is never null, not even before the first save. */ +@Tag("task7") +class PriceHistoryIT extends IntegrationTest { + + @Autowired + private TransactionTemplate transaction; + + @Test + @DisplayName("Assigned ids: saving 1,000 price changes sends no SELECT, only 20 INSERT batches") + void noSelectBeforeEveryInsert() { + Recording recording = record(() -> priceHistory.record(Rows.products(1_000))); + + String sent = "\n" + recording.describe(); + assertThat(recording.roundTrips("select")).as("SELECT round trips" + sent).isZero(); + assertThat(recording.roundTrips("insert into price_change")).as("INSERT round trips" + sent).isEqualTo(20); + assertThat(count("price_change")).as("price changes stored").isEqualTo(1_000); + } + + @Test + @DisplayName("Assigned ids: saveAll() returns the objects you gave it (persist), not copies of them (merge)") + void saveAllPersistsTheSameObjects() { + List changes = List.of( + new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()), + new PriceChange("SKU-2", new BigDecimal("2.00"), Instant.now())); + + List saved = transaction.execute(status -> priceChanges.saveAll(changes)); + + assertThat(saved).as("what saveAll returned").hasSize(2); + assertThat(saved.get(0)).as("the first object saveAll returned").isSameAs(changes.get(0)); + assertThat(saved.get(1)).as("the second object saveAll returned").isSameAs(changes.get(1)); + } + + @Test + @DisplayName("Assigned ids: a price change loaded from the database and saved again is updated, not inserted a second time") + void aLoadedPriceChangeIsUpdated() { + PriceChange original = new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()); + transaction.executeWithoutResult(status -> priceChanges.save(original)); + + PriceChange loaded = priceChanges.findById(original.getId()).orElseThrow(); + loaded.setPrice(new BigDecimal("1.50")); + transaction.executeWithoutResult(status -> priceChanges.save(loaded)); + + assertThat(count("price_change")).as("price change rows").isEqualTo(1); + assertThat(jdbc.queryForObject("select price from price_change", BigDecimal.class)).as("the stored price") + .isEqualByComparingTo("1.50"); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java new file mode 100644 index 0000000..6014c02 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/ProductCsvTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.imports.BadCsvException; +import com.amigoscode.batching.imports.ProductCsv; +import com.amigoscode.batching.product.ProductRow; +import java.io.StringReader; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Unit tests: no Spring, no database. The feed format, which none of the tasks change. */ +@Tag("baseline") +class ProductCsvTest { + + @Test + @DisplayName("CSV: quoted fields keep their commas, quotes and line breaks") + void quotedFields() { + List rows = read(""" + sku,name,price + SKU-1,"Mug, ""large"" + second line",7.50 + SKU-2,Plain,1 + """); + + assertThat(rows).extracting(ProductRow::name).containsExactly("Mug, \"large\"\nsecond line", "Plain"); + assertThat(rows.get(0).price()).isEqualByComparingTo("7.50"); + } + + @Test + @DisplayName("CSV: every column after price is a warehouse, and its value is the stock there") + void warehouseColumns() { + List rows = read(""" + sku,name,price,LON,MAN + SKU-1,Mug,7.50,12,3 + """); + + assertThat(rows.getFirst().stock()).isEqualTo(Map.of("LON", 12, "MAN", 3)); + } + + @Test + @DisplayName("CSV: a price that is not a number is rejected with its line number") + void badPrice() { + assertThatThrownBy(() -> read(""" + sku,name,price + SKU-1,Mug,7.50 + SKU-2,Kettle,cheap + """)) + .isInstanceOf(BadCsvException.class) + .hasMessageContaining("Line 3"); + } + + private static List read(String csv) { + return ProductCsv.read(new StringReader(csv)).toList(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java new file mode 100644 index 0000000..3be1280 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/RewriteIT.java @@ -0,0 +1,54 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import com.amigoscode.batching.support.ServerSide; +import java.math.BigDecimal; +import java.sql.Connection; +import javax.sql.DataSource; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.postgresql.core.BaseConnection; +import org.springframework.beans.factory.annotation.Autowired; + +@Tag("task4") +class RewriteIT extends IntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + @DisplayName("Driver: the connections of the pool have reWriteBatchedInserts switched on") + void theDriverRewritesBatches() throws Exception { + try (Connection connection = dataSource.getConnection()) { + boolean rewrite = connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled(); + + assertThat(rewrite).as("reWriteBatchedInserts, as the Postgres driver sees it").isTrue(); + } + } + + @Test + @DisplayName("Postgres: 2,000 products arrive as multi-row INSERTs, at most 200 INSERT executions instead of 2,000") + void postgresExecutesMultiRowInserts() { + ServerSide.Executed executed = onTheServer(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(executed.rows("insert into product")).as("rows inserted\n" + executed.describe()).isEqualTo(2_000); + assertThat(executed.executions("insert into product")).as("INSERT statements Postgres executed\n" + executed.describe()) + .isLessThanOrEqualTo(200); + } + + @Test + @DisplayName("Postgres: every row still arrives exactly once (2,000 rows, and the prices add up)") + void everyRowArrivesOnce() { + productImporter.importBatched(Rows.products(2_000)); + + assertThat(count("product")).as("products stored").isEqualTo(2_000); + assertThat(jdbc.queryForObject("select count(distinct sku) from product", Long.class)).as("distinct SKUs").isEqualTo(2_000); + // 1.01 + 1.02 + ... + 21.00 + assertThat(jdbc.queryForObject("select sum(price) from product", BigDecimal.class)).as("sum of the prices") + .isEqualByComparingTo("22010.00"); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java new file mode 100644 index 0000000..bfc5189 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/SequenceIdsIT.java @@ -0,0 +1,68 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.Product; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import jakarta.persistence.EntityManagerFactory; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.generator.Generator; +import org.hibernate.id.enhanced.SequenceStyleGenerator; +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; + +@Tag("task2") +class SequenceIdsIT extends IntegrationTest { + + @Autowired + private EntityManagerFactory entityManagerFactory; + + @Test + @DisplayName("Batched: 2,000 products are sent as 40 INSERT batches of 50, not 2,000 single INSERTs") + void insertsAreSentInBatches() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("Batched: the ids come from a sequence, 50 at a time: at most 41 nextval calls for 2,000 products") + void idsComeFromTheSequenceFiftyAtATime() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("select nextval")).as("nextval round trips\n" + recording.describe()) + .isBetween(1, 41); + } + + @Test + @DisplayName("Mapping: Product uses a SEQUENCE generator whose allocationSize equals the sequence's INCREMENT BY") + void allocationSizeMatchesTheSequence() { + Generator generator = entityManagerFactory.unwrap(SessionFactoryImplementor.class) + .getMappingMetamodel().getEntityDescriptor(Product.class).getGenerator(); + + assertThat(generator).as("the id generator of Product").isInstanceOf(SequenceStyleGenerator.class); + SequenceStyleGenerator sequence = (SequenceStyleGenerator) generator; + String name = sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText(); + Long incrementBy = jdbc.queryForObject("select increment_by from pg_sequences where sequencename = ?", Long.class, name); + assertThat(sequence.getOptimizer().getIncrementSize()).as("allocationSize of " + name) + .isGreaterThan(1) + .isEqualTo(incrementBy.intValue()); + } + + @Test + @DisplayName("Ids: two imports with a plain SQL INSERT in between never hand out the same id twice") + void idsNeverClash() { + productImporter.importBatched(Rows.products(1_000, "A-")); + jdbc.update("insert into product (sku, name, price) values ('PLAIN-1', 'Inserted with plain SQL', 1.00)"); + productImporter.importBatched(Rows.products(1_000, "B-")); + + assertThat(jdbc.queryForObject("select count(distinct id) from product", Long.class)) + .as("distinct ids for 2,001 products").isEqualTo(2_001); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java new file mode 100644 index 0000000..3435396 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/DriverOptions.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.support; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.Properties; + +/** + * The tests talk to a Postgres started by Testcontainers, on its own URL. Driver options you add to + * spring.datasource.url in application.properties (everything after the "?") are copied onto that + * URL, so they apply in the tests exactly as they do in ./demo. + */ +final class DriverOptions { + + /** "&reWriteBatchedInserts=true", or "" when the URL in application.properties has no options. */ + static String fromApplicationProperties() { + Properties properties = new Properties(); + try (InputStream in = DriverOptions.class.getResourceAsStream("/application.properties")) { + if (in == null) { + return ""; + } + properties.load(in); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + String url = properties.getProperty("spring.datasource.url", ""); + int query = url.indexOf('?'); + if (query < 0) { + return ""; + } + String options = url.substring(query + 1); + if (options.endsWith("}")) { + options = options.substring(0, options.length() - 1); + } + return options.isBlank() ? "" : "&" + options; + } + + private DriverOptions() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java new file mode 100644 index 0000000..9fa6df2 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/IntegrationTest.java @@ -0,0 +1,86 @@ +package com.amigoscode.batching.support; + +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlRecorder; +import com.amigoscode.batching.price.PriceChangeRepository; +import com.amigoscode.batching.price.PriceHistory; +import com.amigoscode.batching.product.JdbcProductImporter; +import com.amigoscode.batching.product.ProductImporter; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +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 how many round trips an import makes is decided + * by Hibernate, the mapping and the JDBC driver together, and no mock can tell you that. One + * container is shared by every test class. + * + *

The tests never measure time. They count: round trips to the database (SqlRecorder), statements + * Postgres executed (pg_stat_statements), entities in the persistence context (ManagedEntities) and + * rows in the tables. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine") + .withCommand("postgres", "-c", "fsync=off", "-c", "shared_preload_libraries=pg_stat_statements"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", () -> POSTGRES.getJdbcUrl() + DriverOptions.fromApplicationProperties()); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @Autowired + protected ProductImporter productImporter; + + @Autowired + protected JdbcProductImporter jdbcImporter; + + @Autowired + protected PriceHistory priceHistory; + + @Autowired + protected PriceChangeRepository priceChanges; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyTables() { + jdbc.execute("truncate table stock_level, product, price_change"); + } + + /** Runs the work and returns every round trip it made to Postgres. */ + protected Recording record(Runnable work) { + ManagedEntities.reset(); + SqlRecorder.start(); + try { + work.run(); + } catch (RuntimeException e) { + SqlRecorder.stop(); + throw e; + } + return SqlRecorder.stop(); + } + + /** Runs the work and returns what Postgres itself executed while it ran (pg_stat_statements). */ + protected ServerSide.Executed onTheServer(Runnable work) { + return ServerSide.during(jdbc, work); + } + + protected long count(String table) { + return jdbc.queryForObject("select count(*) from " + table, Long.class); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java new file mode 100644 index 0000000..8153d92 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/Rows.java @@ -0,0 +1,42 @@ +package com.amigoscode.batching.support; + +import com.amigoscode.batching.product.ProductRow; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** Rows of a feed, made up in the test. */ +public final class Rows { + + public static List products(int count) { + return products(count, "SKU-"); + } + + /** Different prefixes give different SKUs, so two imports in one test do not clash. */ + public static List products(int count, String skuPrefix) { + List rows = new ArrayList<>(count); + for (int i = 1; i <= count; i++) { + rows.add(new ProductRow(skuPrefix + i, "Product " + i, price(i))); + } + return rows; + } + + /** Every product with stock in three warehouses. {@code day} changes the price and the stock. */ + public static List productsWithStock(int count, int day) { + List rows = new ArrayList<>(count); + for (int i = 1; i <= count; i++) { + rows.add(new ProductRow("SKU-" + i, "Product " + i, price(i).add(BigDecimal.valueOf(day)), + Map.of("GLA", (i + day) % 10, "LON", (i + 2 * day) % 10, "MAN", (i + 3 * day) % 10))); + } + return rows; + } + + /** 1.00, 1.01, ... so the total of the prices tells you whether every row arrived once. */ + public static BigDecimal price(int i) { + return BigDecimal.valueOf(100 + i, 2); + } + + private Rows() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java new file mode 100644 index 0000000..83831bd --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/solution/src/test/java/com/amigoscode/batching/support/ServerSide.java @@ -0,0 +1,53 @@ +package com.amigoscode.batching.support; + +import java.util.List; +import java.util.Locale; +import org.springframework.jdbc.core.JdbcTemplate; + +/** What Postgres itself executed, read from pg_stat_statements. */ +public final class ServerSide { + + /** One statement as Postgres normalised it, how many times it ran, and how many rows it touched. */ + public record Statement(String query, long executions, long rows) { + } + + public record Executed(List statements) { + + /** How many times Postgres ran a statement that starts with the prefix, for example "insert into product". */ + public long executions(String prefix) { + return matching(prefix).stream().mapToLong(Statement::executions).sum(); + } + + public long rows(String prefix) { + return matching(prefix).stream().mapToLong(Statement::rows).sum(); + } + + private List matching(String prefix) { + return statements.stream() + .filter(statement -> statement.query().toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))) + .toList(); + } + + public String describe() { + StringBuilder text = new StringBuilder("Postgres executed:"); + statements.forEach(statement -> text.append(String.format("%n%,d x %s", statement.executions(), + statement.query().length() > 90 ? statement.query().substring(0, 90) + "..." : statement.query()))); + return text.toString(); + } + } + + static Executed during(JdbcTemplate jdbc, Runnable work) { + jdbc.execute("select pg_stat_statements_reset()"); + work.run(); + return new Executed(jdbc.query(""" + select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows + from pg_stat_statements + where dbid = (select oid from pg_database where datname = current_database()) + and query !~* 'pg_stat_statements' + order by calls desc + """, (row, number) -> new Statement(row.getString(1), row.getLong(2), row.getLong(3)))); + } + + private ServerSide() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/16-batch-writes/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/start/.mvn/jvm.config b/java/concepts/junior-mid/16-batch-writes/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/16-batch-writes/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/start/check b/java/concepts/junior-mid/16-batch-writes/start/check new file mode 100755 index 0000000..8ecf048 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/check.cmd b/java/concepts/junior-mid/16-batch-writes/start/check.cmd new file mode 100644 index 0000000..3c5f22a --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/compose.yaml b/java/concepts/junior-mid/16-batch-writes/start/compose.yaml new file mode 100644 index 0000000..b4d4314 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/compose.yaml @@ -0,0 +1,21 @@ +# 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: batch-writes +services: + postgres: + image: postgres:17-alpine + container_name: batch-writes-postgres + # pg_stat_statements counts every statement Postgres executes. ./demo and ./inspect read it to + # show what the database really received, which is not always what the application sent. + command: ["postgres", "-c", "shared_preload_libraries=pg_stat_statements", "-c", "pg_stat_statements.track=all"] + environment: + POSTGRES_DB: batching + POSTGRES_USER: batching + POSTGRES_PASSWORD: batching + ports: + - "5455:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U batching -d batching"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/16-batch-writes/start/demo b/java/concepts/junior-mid/16-batch-writes/start/demo new file mode 100755 index 0000000..4b092c3 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/demo.cmd b/java/concepts/junior-mid/16-batch-writes/start/demo.cmd new file mode 100644 index 0000000..4c7d257 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/inspect b/java/concepts/junior-mid/16-batch-writes/start/inspect new file mode 100755 index 0000000..b86b2a6 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/inspect.cmd b/java/concepts/junior-mid/16-batch-writes/start/inspect.cmd new file mode 100644 index 0000000..fbf084b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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.batching.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/16-batch-writes/start/mvnw b/java/concepts/junior-mid/16-batch-writes/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/start/mvnw.cmd b/java/concepts/junior-mid/16-batch-writes/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/16-batch-writes/start/pom.xml b/java/concepts/junior-mid/16-batch-writes/start/pom.xml new file mode 100644 index 0000000..60b85e2 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + batch-writes + 0.0.1-SNAPSHOT + batch-writes + Batch writes: watch 10,000 rows take 10,000 round trips, then make JPA and JDBC batch them + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + + postgresql + + + + 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/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java new file mode 100644 index 0000000..749a0b5 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/ApiExceptionHandler.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching; + +import com.amigoscode.batching.imports.BadCsvException; +import com.amigoscode.batching.imports.ImportStrategy.UnknownStrategyException; +import org.springframework.dao.DataIntegrityViolationException; +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 becomes a 500. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + /** {@code line} is the line of the CSV file that was rejected, or null. */ + public record ApiError(String code, String message, Integer line) { + } + + @ExceptionHandler(BadCsvException.class) + public ResponseEntity badCsv(BadCsvException e) { + return ResponseEntity.badRequest().body(new ApiError("BAD_CSV", e.getMessage(), e.line())); + } + + @ExceptionHandler(UnknownStrategyException.class) + public ResponseEntity unknownStrategy(UnknownStrategyException e) { + return ResponseEntity.badRequest().body(new ApiError("UNKNOWN_STRATEGY", e.getMessage(), null)); + } + + /** A row the database refused, for example a negative price or a SKU that already exists. */ + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity rejected(DataIntegrityViolationException e) { + String reason = e.getMostSpecificCause().getMessage(); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiError("IMPORT_REJECTED", + "Nothing was imported: the database refused a row. " + firstLine(reason), null)); + } + + private static String firstLine(String text) { + return text == null ? "" : text.lines().findFirst().orElse(""); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java new file mode 100644 index 0000000..29f0898 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/BatchingApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.batching; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BatchingApplication { + + public static void main(String[] args) { + SpringApplication.run(BatchingApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java new file mode 100644 index 0000000..107e080 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/ManagedEntities.java @@ -0,0 +1,39 @@ +package com.amigoscode.batching.db; + +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; +import org.hibernate.Interceptor; + +/** + * Remembers the largest number of entities the persistence context held at any flush. Every + * entity Hibernate manages stays in memory, with a snapshot of its values for dirty checking, + * until the transaction ends or someone calls clear(). This makes that number visible. + * + *

Switched on in application.properties with hibernate.session_factory.interceptor. Hibernate + * calls preFlush with every entity in the persistence context, right before each flush. + * + *

A teaching tool: do not ship a static, shared counter like this in a real application. + */ +public class ManagedEntities implements Interceptor { + + private static final AtomicInteger PEAK = new AtomicInteger(); + + @Override + public void preFlush(Iterator entities) { + int count = 0; + while (entities.hasNext()) { + entities.next(); + count++; + } + PEAK.accumulateAndGet(count, Math::max); + } + + public static void reset() { + PEAK.set(0); + } + + /** The most entities the persistence context held at a flush since the last reset(). */ + public static int peak() { + return PEAK.get(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java new file mode 100644 index 0000000..b051e55 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/Recording.java @@ -0,0 +1,85 @@ +package com.amigoscode.batching.db; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** Everything the application sent to Postgres between SqlRecorder.start() and stop(). */ +public record Recording(List calls, int commits, int rollbacks) { + + /** One statement and everything that was sent with it. */ + public record Shape(String sql, int roundTrips, int rows, Map batchSizes) { + + /** + * "40 x 50" or "39 x 50, 1 x 17": how many batches of each size, biggest first. With more than + * three different sizes, "2,022 of 1 to 50 rows". Empty when nothing was batched. + */ + public String describeBatches() { + if (batchSizes.size() > 3) { + int batches = batchSizes.values().stream().mapToInt(Integer::intValue).sum(); + return String.format("%,d of %,d to %,d rows", batches, + batchSizes.keySet().stream().min(Integer::compare).orElseThrow(), + batchSizes.keySet().stream().max(Integer::compare).orElseThrow()); + } + List parts = new ArrayList<>(); + batchSizes.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(size -> parts.add(String.format("%,d x %,d", size.getValue(), size.getKey()))); + return String.join(", ", parts); + } + } + + public int roundTrips() { + return calls.size(); + } + + public int roundTrips(String sqlPrefix) { + return matching(sqlPrefix).size(); + } + + /** The number of rows (sets of values) sent with statements that start with the prefix. */ + public int rows(String sqlPrefix) { + return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).sum(); + } + + /** The biggest single round trip for statements that start with the prefix, in rows. */ + public int largestBatch(String sqlPrefix) { + return matching(sqlPrefix).stream().mapToInt(SqlCall::rows).max().orElse(0); + } + + public List matching(String sqlPrefix) { + return calls.stream().filter(call -> call.startsWith(sqlPrefix)).toList(); + } + + /** The calls grouped by statement, in the order each statement was first sent. */ + public List shapes() { + Map> grouped = new LinkedHashMap<>(); + for (SqlCall call : calls) { + grouped.computeIfAbsent(call.shape(), ignored -> new ArrayList<>()).add(call); + } + List shapes = new ArrayList<>(); + grouped.forEach((sql, sameSql) -> { + Map batchSizes = new TreeMap<>(); + sameSql.stream() + .filter(call -> call.kind() != SqlCall.Kind.SINGLE) + .forEach(call -> batchSizes.merge(call.rows(), 1, Integer::sum)); + shapes.add(new Shape(sql, sameSql.size(), sameSql.stream().mapToInt(SqlCall::rows).sum(), batchSizes)); + }); + return shapes; + } + + /** A few lines for a failure message: what was sent, grouped by statement. */ + public String describe() { + StringBuilder text = new StringBuilder(String.format("%,d round trips:", roundTrips())); + for (Shape shape : shapes()) { + String sql = shape.sql().length() > 90 ? shape.sql().substring(0, 90) + "..." : shape.sql(); + text.append(String.format("%n%,d x %s", shape.roundTrips(), sql)); + if (!shape.batchSizes().isEmpty()) { + text.append(" [batches: ").append(shape.describeBatches()).append("]"); + } + } + return text.toString(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java new file mode 100644 index 0000000..592da9c --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlCall.java @@ -0,0 +1,29 @@ +package com.amigoscode.batching.db; + +import java.util.Locale; + +/** + * One round trip from the application to Postgres: one execute() of one statement, one + * executeBatch() of a JDBC batch, or one COPY. {@code rows} is how many sets of values it carried: + * 1 for a plain statement, the batch size for a batch, the number of rows for a COPY. + */ +public record SqlCall(String sql, Kind kind, int rows) { + + public enum Kind { + /** execute(), executeQuery() or executeUpdate(): one statement, one set of values. */ + SINGLE, + /** executeBatch(): the same statement with many sets of values, sent together. */ + BATCH, + /** COPY ... FROM STDIN: one statement, the rows stream after it. */ + COPY + } + + /** The statement in lower case, on one line. */ + public String shape() { + return sql.strip().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT); + } + + public boolean startsWith(String prefix) { + return shape().startsWith(prefix.toLowerCase(Locale.ROOT)); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java new file mode 100644 index 0000000..a68fd9c --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/db/SqlRecorder.java @@ -0,0 +1,219 @@ +package com.amigoscode.batching.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.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import javax.sql.DataSource; +import org.postgresql.PGConnection; +import org.postgresql.copy.CopyIn; +import org.postgresql.copy.CopyManager; +import org.postgresql.core.BaseConnection; +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 every round trip the application makes to Postgres, whoever makes it: Hibernate, Spring + * Data, JdbcTemplate or a COPY. ./demo and the tests use it to answer "how many times did this + * import talk to the database, and how many rows did each trip carry?" + * + * SqlRecorder.start(); + * ... run the import ... + * Recording recording = SqlRecorder.stop(); + * + * It wraps the DataSource, so it sees exactly what reaches the JDBC driver: one execute() is one + * round trip, one executeBatch() is one round trip however many rows were added to the batch. + * (Hibernate's own statement counters count a batch differently, which is why they are not used.) + * + *

A teaching tool: do not ship a static, shared recorder like this in a real application. + */ +public final class SqlRecorder { + + private static final Object LOCK = new Object(); + private static final Set EXECUTE = Set.of("execute", "executeQuery", "executeUpdate", "executeLargeUpdate"); + private static final Set EXECUTE_BATCH = Set.of("executeBatch", "executeLargeBatch"); + + private static List calls; + private static int commits; + private static int rollbacks; + + public static void start() { + synchronized (LOCK) { + calls = new ArrayList<>(); + commits = 0; + rollbacks = 0; + } + } + + /** Stops recording and returns what was sent since start(). */ + public static Recording stop() { + synchronized (LOCK) { + Recording recording = new Recording(calls == null ? List.of() : List.copyOf(calls), commits, rollbacks); + calls = null; + return recording; + } + } + + private static void record(String sql, SqlCall.Kind kind, int rows) { + synchronized (LOCK) { + if (calls != null) { + calls.add(new SqlCall(sql, kind, rows)); + } + } + } + + private static void recordEnd(boolean commit) { + synchronized (LOCK) { + if (calls != null) { + if (commit) { + commits++; + } else { + rollbacks++; + } + } + } + } + + /** 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 && !(bean instanceof RecordingDataSource) + ? 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) -> { + String name = method.getName(); + if (name.equals("unwrap") && args[0] == PGConnection.class) { + return watchCopy(connection.unwrap(PGConnection.class)); + } + Object result = call(connection, method, args); + if (name.equals("commit")) { + recordEnd(true); + } else if (name.equals("rollback") && args == null) { + recordEnd(false); + } else if (name.equals("prepareStatement") && result instanceof PreparedStatement statement) { + return watch(statement, (String) args[0]); + } else if (name.equals("createStatement") && result instanceof Statement statement) { + return watch(statement); + } + return result; + }); + } + + private static PreparedStatement watch(PreparedStatement statement, String sql) { + int[] batched = {0}; + return proxy(PreparedStatement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.equals("addBatch") && args == null) { + batched[0]++; + } else if (name.equals("clearBatch")) { + batched[0] = 0; + } else if (EXECUTE_BATCH.contains(name)) { + record(sql, SqlCall.Kind.BATCH, batched[0]); + batched[0] = 0; + } else if (EXECUTE.contains(name) && args == null) { + record(sql, SqlCall.Kind.SINGLE, 1); + } + return call(statement, method, args); + }); + } + + /** A plain Statement: the SQL is passed to execute() itself. */ + private static Statement watch(Statement statement) { + List batch = new ArrayList<>(); + return proxy(Statement.class, (proxy, method, args) -> { + String name = method.getName(); + if (name.equals("addBatch") && args != null) { + batch.add((String) args[0]); + } else if (EXECUTE_BATCH.contains(name) && !batch.isEmpty()) { + record(batch.getFirst(), SqlCall.Kind.BATCH, batch.size()); + batch.clear(); + } else if (EXECUTE.contains(name) && args != null && args[0] instanceof String sql) { + record(sql, SqlCall.Kind.SINGLE, 1); + } + return call(statement, method, args); + }); + } + + /** COPY does not go through a Statement at all: it is the driver's CopyManager. */ + private static PGConnection watchCopy(PGConnection connection) { + return proxy(PGConnection.class, (proxy, method, args) -> { + if (method.getName().equals("getCopyAPI")) { + return new RecordingCopyManager((BaseConnection) connection); + } + return call(connection, method, args); + }); + } + + private static T proxy(Class type, InvocationHandler handler) { + return type.cast(Proxy.newProxyInstance(SqlRecorder.class.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(); + } + } + } + + /** Records a COPY when it ends, with the number of rows Postgres says it stored. */ + private static final class RecordingCopyManager extends CopyManager { + + RecordingCopyManager(BaseConnection connection) throws SQLException { + super(connection); + } + + @Override + public CopyIn copyIn(String sql) throws SQLException { + CopyIn copy = super.copyIn(sql); + return RecordingDataSource.proxy(CopyIn.class, (proxy, method, args) -> { + Object result = RecordingDataSource.call(copy, method, args); + if (method.getName().equals("endCopy")) { + record(sql, SqlCall.Kind.COPY, (int) (long) (Long) result); + } + return result; + }); + } + + } + + private SqlRecorder() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java new file mode 100644 index 0000000..dce5c1a --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Db.java @@ -0,0 +1,52 @@ +package com.amigoscode.batching.demo; + +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. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5455/batching"); + static final String USER = env("DB_USER", "batching"); + static final String PASSWORD = env("DB_PASSWORD", "batching"); + + private Db() { + } + + /** + * A connection for the tools themselves. pg_stat_statements is told to ignore it, so the queries + * ./demo and ./inspect run to count things do not show up next to the application's statements. + */ + static Connection connect() throws SQLException { + Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); + try (Statement statement = connection.createStatement()) { + statement.execute("set pg_stat_statements.track = 'none'"); + } catch (SQLException notLoadedOrNotAllowed) { + // Without pg_stat_statements there is nothing to hide from. + } + return connection; + } + + /** 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/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java new file mode 100644 index 0000000..edd5b0e --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Demo.java @@ -0,0 +1,441 @@ +package com.amigoscode.batching.demo; + +import com.amigoscode.batching.BatchingApplication; +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlCall; +import com.amigoscode.batching.db.SqlRecorder; +import com.amigoscode.batching.price.PriceChange; +import com.amigoscode.batching.product.Product; +import com.amigoscode.batching.product.StockLevel; +import jakarta.persistence.EntityManagerFactory; +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.util.ArrayList; +import java.util.List; +import java.util.Locale; +import javax.sql.DataSource; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.generator.Generator; +import org.hibernate.id.IdentityGenerator; +import org.hibernate.id.enhanced.SequenceStyleGenerator; +import org.postgresql.core.BaseConnection; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; + +/** + * Starts the real application, sends it a generated CSV feed over HTTP, and prints how many round + * trips the import made to Postgres, what Postgres executed, and how many entities Hibernate held in + * memory. Run it with ./demo (or .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final List STRATEGIES = List.of("one-by-one", "batched", "rewrite", "jdbc", "copy"); + private static final int WIDTH = 74; + + private record Options(String strategy, int rows, boolean stock, boolean prices, Boolean rewrite, boolean sql) { + + /** The strategy the application knows: "rewrite" is "batched" with the driver setting on. */ + String appStrategy() { + return strategy.equals("rewrite") ? "batched" : strategy; + } + + boolean jpa() { + return prices || !(strategy.equals("jdbc") || strategy.equals("copy")); + } + } + + /** One HTTP request and everything it caused. */ + private record Phase(String title, int status, String body, Recording recording, + List executed, int peakEntities, long millis) { + + int rowsWritten() { + return recording.calls().stream() + .filter(call -> call.startsWith("insert") || call.startsWith("update") || call.startsWith("copy")) + .mapToInt(SqlCall::rows) + .sum(); + } + } + + 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", + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--spring.web.error.include-message=always")); + Boolean rewrite = options.strategy().equals("rewrite") ? Boolean.TRUE : options.rewrite(); + + SpringApplication app = new SpringApplication(BatchingApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + if (rewrite != null) { + // An option on the URL beats a driver property, so the override goes on the URL itself. + app.addInitializers(context -> { + var environment = context.getEnvironment(); + String url = withRewrite(environment.getProperty("spring.datasource.url", Db.URL), rewrite); + environment.getPropertySources().addFirst(new MapPropertySource("demo-rewrite", + java.util.Map.of("spring.datasource.url", url))); + }); + } + try (ConfigurableApplicationContext context = app.run(springArgs.toArray(String[]::new))) { + run(options, context); + } + } + + private static void run(Options options, ConfigurableApplicationContext context) throws Exception { + String baseUrl = "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + int batchSize = context.getEnvironment().getProperty("spring.jpa.properties.hibernate.jdbc.batch_size", Integer.class, 0); + + // A throwaway request first, so the import is not slowed down by start-up work. + http.send(HttpRequest.newBuilder(URI.create(baseUrl + "/warm-up")).build(), HttpResponse.BodyHandlers.discarding()); + + printHeader(options, context, batchSize); + + List phases = new ArrayList<>(); + try (Connection server = Db.connect()) { + boolean serverStats = ServerStats.available(server); + if (options.prices()) { + phases.add(send(http, server, serverStats, "PRICE HISTORY: " + number(options.rows()) + " price changes, saveAll()", + "POST", baseUrl + "/api/imports/prices", Feed.products(options.rows(), false))); + } else { + phases.add(send(http, server, serverStats, "IMPORT: " + number(options.rows()) + " new products" + + (options.stock() ? ", each with 3 stock levels" : ""), + "POST", baseUrl + "/api/imports/products?strategy=" + options.appStrategy(), + Feed.products(options.rows(), options.stock()))); + if (options.stock() && phases.getFirst().status() == 200) { + phases.add(send(http, server, serverStats, "UPDATE: the next day's feed, a new price and new stock for every product", + "PUT", baseUrl + "/api/imports/products", Feed.nextDay(options.rows()))); + } + } + if (!serverStats) { + System.out.println("(pg_stat_statements is not loaded in this Postgres, so the server side is not shown."); + System.out.println(" The compose.yaml of this project loads it: docker compose down, then docker compose up -d.)"); + System.out.println(); + } + } + + for (Phase phase : phases) { + print(phase, options.sql()); + } + + long products; + long stockLevels; + long priceChanges; + try (Connection connection = Db.connect()) { + products = count(connection, "product"); + stockLevels = count(connection, "stock_level"); + priceChanges = count(connection, "price_change"); + } + System.out.println("Rows in the database: " + number(products) + " products, " + number(stockLevels) + + " stock levels, " + number(priceChanges) + " price changes"); + System.out.println(); + + printResults(options, phases, batchSize, options.prices() ? priceChanges : products); + } + + private static long count(Connection connection, String table) throws java.sql.SQLException { + try (var statement = connection.createStatement(); var result = statement.executeQuery("select count(*) from " + table)) { + result.next(); + return result.getLong(1); + } + } + + private static Phase send(HttpClient http, Connection server, boolean serverStats, String title, + String method, String url, String csv) throws Exception { + HttpRequest request = HttpRequest.newBuilder(URI.create(url)) + .header("Content-Type", "text/csv") + .method(method, HttpRequest.BodyPublishers.ofString(csv)) + .build(); + if (serverStats) { + ServerStats.reset(server); + } + ManagedEntities.reset(); + SqlRecorder.start(); + long started = System.nanoTime(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + long millis = (System.nanoTime() - started) / 1_000_000; + Recording recording = SqlRecorder.stop(); + List executed = serverStats ? ServerStats.read(server) : List.of(); + return new Phase(title, response.statusCode(), response.body(), recording, executed, ManagedEntities.peak(), millis); + } + + /** The URL with reWriteBatchedInserts set to the given value, whatever it said before. */ + private static String withRewrite(String url, boolean on) { + String clean = url.replaceAll("(?i)([?&])reWriteBatchedInserts=[^&]*&?", "$1").replaceAll("[?&]$", ""); + return clean + (clean.contains("?") ? "&" : "?") + "reWriteBatchedInserts=" + on; + } + + private static void printHeader(Options options, ConfigurableApplicationContext context, int batchSize) { + // Ask the driver itself: the option can come from the URL or from a driver property. + String rewrite = "?"; + try (Connection connection = context.getBean(DataSource.class).getConnection()) { + rewrite = String.valueOf(connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled()); + } catch (Exception ignored) { + // Not the Postgres driver: leave it as "?". + } + var environment = context.getEnvironment(); + System.out.println(); + System.out.println("Strategy: " + options.strategy() + (options.prices() ? " (ignored: --prices always uses saveAll)" : "") + + " | rows: " + number(options.rows())); + System.out.println("Settings: hibernate.jdbc.batch_size=" + (batchSize == 0 ? "(not set)" : batchSize) + + " | order_inserts=" + environment.getProperty("spring.jpa.properties.hibernate.order_inserts", "false") + + " | order_updates=" + environment.getProperty("spring.jpa.properties.hibernate.order_updates", "false") + + " | reWriteBatchedInserts=" + rewrite); + SessionFactoryImplementor hibernate = context.getBean(EntityManagerFactory.class).unwrap(SessionFactoryImplementor.class); + if (options.prices()) { + System.out.println("PriceChange ids: " + describe(generator(hibernate, PriceChange.class))); + } else if (options.jpa()) { + System.out.println("Product ids: " + describe(generator(hibernate, Product.class))); + if (options.stock()) { + System.out.println("StockLevel ids: " + describe(generator(hibernate, StockLevel.class))); + } + } else { + System.out.println("Product ids: the column default, nextval('product_seq') or the identity. No entities."); + } + System.out.println(); + } + + private static Generator generator(SessionFactoryImplementor hibernate, Class entity) { + return hibernate.getMappingMetamodel().getEntityDescriptor(entity).getGenerator(); + } + + private static String describe(Generator generator) { + if (generator == null) { + return "assigned in Java: Hibernate generates nothing"; + } + if (generator instanceof IdentityGenerator) { + return "IDENTITY. Postgres makes each id while it runs the INSERT"; + } + if (generator instanceof SequenceStyleGenerator sequence) { + int allocation = sequence.getOptimizer().getIncrementSize(); + return "SEQUENCE " + sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText() + + ", allocationSize " + allocation + " (" + sequence.getOptimizer().getClass().getSimpleName() + + ": " + (allocation == 1 ? "one nextval per row" : "one nextval per " + allocation + " ids") + ")"; + } + String name = generator.getClass().getSimpleName(); + if (name.equals("UuidGenerator")) { + return "UuidGenerator. Hibernate makes a UUID in memory when the entity is persisted"; + } + return name.equals("Assigned") ? "assigned in Java: Hibernate generates nothing" : name; + } + + private static void print(Phase phase, boolean sql) { + System.out.println(phase.title()); + System.out.println("=".repeat(Math.min(phase.title().length(), WIDTH + 20))); + if (phase.status() != 200) { + System.out.println(); + System.out.println(" HTTP " + phase.status() + ": " + phase.body()); + System.out.println(); + return; + } + Recording recording = phase.recording(); + System.out.println(); + System.out.println("What the application sent, counted at the JDBC driver (one execute or executeBatch = one round trip)"); + List rows = new ArrayList<>(); + rows.add(new String[] {"round trips", "rows", "batches (count x size)", "statement"}); + for (Recording.Shape shape : recording.shapes()) { + rows.add(new String[] {number(shape.roundTrips()), number(shape.rows()), shape.describeBatches(), clip(shape.sql())}); + } + Table.print(rows, 0, 1); + if (sql) { + System.out.println(); + System.out.println("The first 25 round trips, in the order they were sent"); + List calls = recording.calls(); + for (int i = 0; i < Math.min(25, calls.size()); i++) { + SqlCall call = calls.get(i); + System.out.printf(" %4d %-6s %4d row%s %s%n", i + 1, call.kind().name().toLowerCase(Locale.ROOT), + call.rows(), call.rows() == 1 ? " " : "s", clip(call.shape())); + } + } + if (!phase.executed().isEmpty()) { + System.out.println(); + System.out.println("What Postgres executed, counted by the server (pg_stat_statements)"); + List executed = new ArrayList<>(); + executed.add(new String[] {"executions", "rows", "rows each", "statement"}); + for (ServerStats.Executed statement : phase.executed()) { + long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls(); + executed.add(new String[] {number(statement.calls()), number(statement.rows()), number(each), + clip(ServerStats.shorten(statement.query()))}); + } + Table.print(executed, 0, 1, 2); + } + System.out.println(); + System.out.println("Round trips: " + number(recording.roundTrips())); + System.out.println("Commits: " + number(recording.commits())); + System.out.println("Peak entities held: " + number(phase.peakEntities()) + + " (the most entities in Hibernate's persistence context at one flush)"); + System.out.println("Time taken: " + number(phase.millis()) + " ms"); + System.out.println(); + } + + private static void printResults(Options options, List phases, int batchSize, long rowsStored) { + List problems = new ArrayList<>(); + for (Phase phase : phases) { + if (phase.status() != 200) { + problems.add("FAILED. " + phase.title().split(":")[0] + " returned HTTP " + phase.status() + "."); + continue; + } + Recording recording = phase.recording(); + String what = phase.title().split(":")[0].toLowerCase(Locale.ROOT); + int selects = recording.roundTrips("select") - recording.roundTrips("select nextval"); + if (options.prices() && selects > 0) { + problems.add(number(selects) + " SELECTS. saveAll() looked up every price change before inserting it."); + } + if (recording.commits() > 1) { + problems.add(number(recording.commits()) + " COMMITS. Every row was its own transaction."); + } + int rowsWritten = phase.rowsWritten(); + if (recording.roundTrips() * 10L > rowsWritten) { + problems.add(number(recording.roundTrips()) + " ROUND TRIPS. The " + what + " wrote " + number(rowsWritten) + + " rows, " + perTrip(rowsWritten, recording.roundTrips()) + " per round trip."); + } + boolean importPhase = phase == phases.getFirst() && !options.prices() && options.jpa(); + if (importPhase && batchSize > 0 && phase.peakEntities() > 4 * batchSize) { + problems.add(number(phase.peakEntities()) + " ENTITIES IN MEMORY. The persistence context held the whole " + + what + " until it ended."); + } + } + if (problems.isEmpty()) { + Phase first = phases.getFirst(); + StringBuilder ok = new StringBuilder("RESULT: OK. " + number(rowsStored) + " rows in " + + roundTrips(first.recording().roundTrips())); + if (phases.size() > 1) { + ok.append(", updated in ").append(roundTrips(phases.get(1).recording().roundTrips())); + } + if (!options.prices() && options.jpa()) { + ok.append(", at most ").append(number(first.peakEntities())).append(" entities in memory"); + } + System.out.println(ok.append('.')); + } else { + problems.forEach(problem -> System.out.println("RESULT: " + problem)); + } + System.out.println(); + } + + private static String roundTrips(int count) { + return number(count) + (count == 1 ? " round trip" : " round trips"); + } + + private static String perTrip(int rows, int roundTrips) { + double average = roundTrips == 0 ? 0 : (double) rows / roundTrips; + return String.format(Locale.US, "%.1f", average); + } + + private static String clip(String sql) { + return sql.length() > WIDTH ? sql.substring(0, WIDTH - 3) + "..." : sql; + } + + static String number(long value) { + return String.format(Locale.US, "%,d", value); + } + + private static Options parse(String[] args) { + String strategy = "batched"; + int rows = 10_000; + boolean stock = false; + boolean prices = false; + Boolean rewrite = null; + boolean sql = false; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--strategy" -> { + strategy = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!STRATEGIES.contains(strategy)) { + throw new IllegalArgumentException("Unknown strategy '" + strategy + "'. Use one of: " + String.join(", ", STRATEGIES)); + } + } + case "--rows" -> rows = number(value(args, ++i, arg), arg, 1, 100_000); + case "--stock" -> stock = true; + case "--prices" -> prices = true; + case "--rewrite" -> { + String value = value(args, ++i, arg).toLowerCase(Locale.ROOT); + if (!value.equals("on") && !value.equals("off")) { + throw new IllegalArgumentException("--rewrite must be on or off, got: " + value); + } + rewrite = value.equals("on"); + } + case "--sql" -> sql = true; + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + if (stock && prices) { + throw new IllegalArgumentException("Use --stock or --prices, not both."); + } + if (stock && (strategy.equals("jdbc") || strategy.equals("copy"))) { + throw new IllegalArgumentException("--stock needs JPA: the " + strategy + " importer does not write stock levels (that is one of its trade-offs)."); + } + return new Options(strategy, rows, stock, prices, rewrite, 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.replace(",", "").replace("_", "")); + if (number < min || number > max) { + throw new NumberFormatException(); + } + return number; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(option + " must be a number from " + min + " to " + number(max) + ", got: " + value); + } + } + + private static void printHelp() { + System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])"); + System.out.println(); + System.out.println(" --rows how many products the feed has (default: 10000)"); + System.out.println(" --strategy how they reach the database (default: batched)"); + System.out.println(" one-by-one JPA, one transaction per row (never changes: the reference)"); + System.out.println(" batched JPA, one transaction, saveAll (Tasks 2 to 6 change this)"); + System.out.println(" rewrite batched, with reWriteBatchedInserts=true for this run"); + System.out.println(" jdbc JdbcTemplate.batchUpdate, no entities (Task 8)"); + System.out.println(" copy Postgres COPY through the driver's CopyManager (Task 8)"); + System.out.println(" --rewrite on|off force reWriteBatchedInserts for this run (default: application.properties)"); + System.out.println(" --stock every product gets 3 stock levels, then a second feed updates them all"); + System.out.println(" --prices write the price history instead: ids are UUIDs made in Java"); + System.out.println(" --sql also list the first 25 round trips, in order"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --strategy rewrite"); + System.out.println(" ./demo --stock --rows 2000"); + System.out.println(" ./demo --prices --rows 1000"); + System.out.println(" ./demo --strategy copy --rows 100000"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java new file mode 100644 index 0000000..461ff10 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Feed.java @@ -0,0 +1,55 @@ +package com.amigoscode.batching.demo; + +import java.math.BigDecimal; +import java.util.List; + +/** Builds the supplier's CSV feed. Same input every time, so two runs can be compared. */ +final class Feed { + + static final List WAREHOUSES = List.of("GLA", "LON", "MAN"); + + private static final String[] COLOURS = {"Black", "White", "Red", "Blue", "Green", "Grey", "Yellow", "Navy"}; + private static final String[] THINGS = {"mug", "kettle", "lamp", "chair", "desk", "pillow", "towel", "teapot", "vase", "clock"}; + + private Feed() { + } + + /** The first feed: new products, optionally with stock in three warehouses. */ + static String products(int rows, boolean withStock) { + return build(rows, withStock, 0); + } + + /** The next day's feed: the same SKUs, every price up by 10% and different stock. */ + static String nextDay(int rows) { + return build(rows, true, 1); + } + + private static String build(int rows, boolean withStock, int day) { + StringBuilder csv = new StringBuilder(rows * 48); + csv.append("sku,name,price"); + if (withStock) { + WAREHOUSES.forEach(warehouse -> csv.append(',').append(warehouse)); + } + csv.append('\n'); + for (int i = 1; i <= rows; i++) { + BigDecimal price = BigDecimal.valueOf(100 + (i * 37L) % 9900, 2); + if (day > 0) { + price = price.multiply(new BigDecimal("1.10")).setScale(2, java.math.RoundingMode.HALF_UP); + } + csv.append(sku(i)).append(',') + .append(COLOURS[i % COLOURS.length]).append(' ').append(THINGS[i % THINGS.length]).append(" no. ").append(i) + .append(',').append(price.toPlainString()); + if (withStock) { + for (int w = 0; w < WAREHOUSES.size(); w++) { + csv.append(',').append((i * (w + 3) + day * 5) % 40); + } + } + csv.append('\n'); + } + return csv.toString(); + } + + static String sku(int i) { + return String.format("SKU-%06d", i); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java new file mode 100644 index 0000000..69cd8fa --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Inspect.java @@ -0,0 +1,149 @@ +package com.amigoscode.batching.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Shows what the database holds after a ./demo run: how each table gets its ids, the sequences and + * how far they have moved, how far apart the stored ids are, and every statement Postgres executed + * for the last request of the demo (pg_stat_statements). Run it with ./inspect (or .\inspect on + * Windows) after ./demo. + */ +public final class Inspect { + + private static final String ID_COLUMNS = """ + select c.table_name as "table", + c.data_type as "type", + case when c.is_identity = 'YES' then 'IDENTITY: Postgres makes it while it runs the INSERT' + when c.column_default like 'nextval%' then 'DEFAULT ' || c.column_default + else 'none: the application must send it' end as "where the id comes from" + from information_schema.columns c + where c.table_schema = current_schema() + and c.table_name in ('product', 'stock_level', 'price_change') + and c.column_name = 'id' + order by c.table_name + """; + + private static final String SEQUENCES = """ + select sequencename as "sequence", + increment_by as "increment by", + coalesce(last_value::text, '(never used)') as "last value handed out" + from pg_sequences + where schemaname = current_schema() + order by sequencename + """; + + private static final String IDS = """ + with ids as ( + select 'product' as t, null::text as uuid, id as n from product + union all select 'stock_level', null, id from stock_level + union all select 'price_change', id::text, null from price_change + ), + steps as ( + select t, n - lag(n) over (partition by t order by n) as step from ids where n is not null + ), + common as ( + select t, step, count(*) as times, + row_number() over (partition by t order by count(*) desc, step) as rank + from steps where step is not null group by t, step + ) + select tables.t as "table", + to_char(count(i.t), 'FM999,999,990') as "rows", + coalesce(min(i.n)::text, min(i.uuid), '') as "lowest id", + coalesce(max(i.n)::text, max(i.uuid), '') as "highest id", + coalesce((select string_agg('+' || c.step || ' (' || to_char(c.times, 'FM999,999,990') || 'x)', ', ' order by c.rank) + from common c where c.t = tables.t and c.rank <= 3), '') as "most common gaps between neighbouring ids" + from (values ('product'), ('stock_level'), ('price_change')) as tables (t) + left join ids i on i.t = tables.t + group by tables.t + order by tables.t + """; + + 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("Run it after ./demo. It reads the database only, and changes nothing."); + return; + } + if (!Db.isUp()) { + return; + } + try (Connection connection = Db.connect()) { + if (!tablesExist(connection)) { + System.out.println(); + System.out.println("The tables do not exist yet. Run ./demo first."); + System.out.println(); + return; + } + System.out.println(); + System.out.println("WHERE EACH TABLE GETS ITS IDS (information_schema.columns)"); + printTable(connection, ID_COLUMNS); + System.out.println(); + System.out.println("SEQUENCES (pg_sequences)"); + if (printTable(connection, SEQUENCES) == 0) { + System.out.println(" none."); + } + System.out.println(); + System.out.println("THE ROWS AND THEIR IDS"); + printTable(connection, IDS); + System.out.println(); + System.out.println("WHAT POSTGRES EXECUTED FOR THE LAST REQUEST OF ./demo (pg_stat_statements)"); + if (!ServerStats.available(connection)) { + System.out.println(" pg_stat_statements is not loaded in this Postgres. The compose.yaml of this project loads it:"); + System.out.println(" docker compose down, then docker compose up -d."); + } else { + List rows = new ArrayList<>(); + rows.add(new String[] {"executions", "rows", "rows each", "statement"}); + for (ServerStats.Executed statement : ServerStats.read(connection)) { + long each = statement.calls() == 0 ? 0 : statement.rows() / statement.calls(); + String query = ServerStats.shorten(statement.query()); + rows.add(new String[] {Demo.number(statement.calls()), Demo.number(statement.rows()), Demo.number(each), + query.length() > 90 ? query.substring(0, 87) + "..." : query}); + } + Table.print(rows, 0, 1, 2); + } + System.out.println(); + } + } + + private static boolean tablesExist(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("select to_regclass('product') is not null")) { + result.next(); + return result.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) { + Table.print(rows); + } + return rows.size() - 1; + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java new file mode 100644 index 0000000..e5ed34b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/ServerStats.java @@ -0,0 +1,72 @@ +package com.amigoscode.batching.demo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads pg_stat_statements: what Postgres itself executed, counted on the server. The application + * side (SqlRecorder) counts round trips; this side counts statements. They are not the same number + * once the driver starts rewriting batches. + */ +final class ServerStats { + + /** One statement as Postgres normalised it ($1, $2 for the values), how often it ran, and the rows. */ + record Executed(String query, long calls, long rows) { + } + + private static final String READ = """ + select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows + from pg_stat_statements + where dbid = (select oid from pg_database where datname = current_database()) + and query !~* 'pg_stat_statements|pg_catalog|information_schema|pg_sequences|pg_class|pg_attribute' + and query ~* '^\\s*(insert|update|delete|select|copy|with)' + order by calls desc, query + """; + + private ServerStats() { + } + + /** False when the extension is not loaded (compose.yaml loads it; another Postgres may not). */ + static boolean available(Connection connection) { + try (Statement statement = connection.createStatement()) { + statement.execute("select 1 from pg_stat_statements limit 1"); + return true; + } catch (SQLException e) { + return false; + } + } + + static void reset(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("select pg_stat_statements_reset()"); + } + } + + static List read(Connection connection) throws SQLException { + List executed = new ArrayList<>(); + try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(READ)) { + while (result.next()) { + executed.add(new Executed(result.getString(1), result.getLong(2), result.getLong(3))); + } + } + return executed; + } + + /** A multi-row INSERT has one "($1,$2,$3)" per row: keeps the first one and replaces the rest with "...". */ + static String shorten(String query) { + int values = query.toLowerCase().indexOf(" values ("); + if (values < 0) { + return query; + } + int firstEnd = query.indexOf(')', values); + int rest = query.indexOf("),(", values); + if (rest < 0) { + rest = query.indexOf("), (", values); + } + return rest < 0 || rest != firstEnd ? query : query.substring(0, firstEnd + 1) + ",..."; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java new file mode 100644 index 0000000..15e2cda --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/demo/Table.java @@ -0,0 +1,41 @@ +package com.amigoscode.batching.demo; + +import java.util.Arrays; +import java.util.List; + +/** Prints rows as a plain text table. The first row is the header. */ +final class Table { + + private Table() { + } + + /** {@code rightAligned} are the column numbers to align to the right (the numbers). */ + static void print(List rows, int... rightAligned) { + if (rows.size() == 1) { + System.out.println(" (nothing)"); + return; + } + int[] widths = new int[rows.getFirst().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++) { + int column = c; + boolean right = r > 0 && Arrays.stream(rightAligned).anyMatch(n -> n == column); + line.append(String.format("%" + (right ? "" : "-") + 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()); + } + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java new file mode 100644 index 0000000..c75efc6 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/BadCsvException.java @@ -0,0 +1,16 @@ +package com.amigoscode.batching.imports; + +/** A line of the uploaded CSV that cannot be read. Becomes a 400 with the line number. */ +public class BadCsvException extends RuntimeException { + + private final int line; + + public BadCsvException(int line, String problem) { + super("Line " + line + ": " + problem); + this.line = line; + } + + public int line() { + return line; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java new file mode 100644 index 0000000..c4c3599 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportController.java @@ -0,0 +1,47 @@ +package com.amigoscode.batching.imports; + +import java.io.Reader; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * The supplier's feed arrives as CSV in the request body (see ProductCsv for the format). + * + *

+ * POST /api/imports/products?strategy=batched   new products: one-by-one | batched | jdbc | copy
+ * PUT  /api/imports/products                    same SKUs again: new prices and new stock
+ * POST /api/imports/prices                      one price change per row, into the price history
+ * 
+ */ +@RestController +@RequestMapping("/api/imports") +public class ImportController { + + public record ImportResponse(String strategy, long rows) { + } + + private final ImportService imports; + + public ImportController(ImportService imports) { + this.imports = imports; + } + + @PostMapping(path = "/products", consumes = "text/csv") + public ImportResponse importProducts(@RequestParam(defaultValue = "batched") String strategy, Reader body) { + ImportStrategy chosen = ImportStrategy.from(strategy); + return new ImportResponse(chosen.label(), imports.importProducts(chosen, ProductCsv.read(body))); + } + + @PutMapping(path = "/products", consumes = "text/csv") + public ImportResponse updateProducts(Reader body) { + return new ImportResponse("update", imports.updateProducts(ProductCsv.read(body).toList())); + } + + @PostMapping(path = "/prices", consumes = "text/csv") + public ImportResponse recordPrices(Reader body) { + return new ImportResponse("price-history", imports.recordPrices(ProductCsv.read(body).toList())); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java new file mode 100644 index 0000000..a3276d9 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportService.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.imports; + +import com.amigoscode.batching.price.PriceHistory; +import com.amigoscode.batching.product.JdbcProductImporter; +import com.amigoscode.batching.product.ProductImporter; +import com.amigoscode.batching.product.ProductRow; +import java.util.List; +import org.springframework.stereotype.Service; + +/** Picks the importer. Deliberately not transactional: each importer decides its own transactions. */ +@Service +public class ImportService { + + private final ProductImporter jpa; + private final JdbcProductImporter jdbc; + private final PriceHistory priceHistory; + + public ImportService(ProductImporter jpa, JdbcProductImporter jdbc, PriceHistory priceHistory) { + this.jpa = jpa; + this.jdbc = jdbc; + this.priceHistory = priceHistory; + } + + public long importProducts(ImportStrategy strategy, Iterable rows) { + return switch (strategy) { + case ONE_BY_ONE -> jpa.importOneByOne(rows); + case BATCHED -> jpa.importBatched(rows); + case JDBC -> jdbc.batchInsert(rows); + case COPY -> jdbc.copy(rows); + }; + } + + public long updateProducts(List rows) { + return jpa.updateAll(rows); + } + + public long recordPrices(List rows) { + return priceHistory.record(rows); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java new file mode 100644 index 0000000..905bca8 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ImportStrategy.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.imports; + +import java.util.Arrays; +import java.util.Locale; +import java.util.stream.Collectors; + +/** How the rows of an import reach the database. Chosen per request with ?strategy=. */ +public enum ImportStrategy { + + /** JPA, one transaction per row. Stays as it is, so you can always compare against it. */ + ONE_BY_ONE, + /** JPA, the whole file in one transaction with saveAll. Tasks 2 to 6. */ + BATCHED, + /** JdbcTemplate.batchUpdate, no entities. Task 8. */ + JDBC, + /** Postgres COPY through the driver's CopyManager. Task 8. */ + COPY; + + public String label() { + return name().toLowerCase(Locale.ROOT).replace('_', '-'); + } + + public static ImportStrategy from(String value) { + return Arrays.stream(values()) + .filter(strategy -> strategy.label().equals(value == null ? "" : value.trim().toLowerCase(Locale.ROOT))) + .findFirst() + .orElseThrow(() -> new UnknownStrategyException(value)); + } + + public static String labels() { + return Arrays.stream(values()).map(ImportStrategy::label).collect(Collectors.joining(", ")); + } + + public static class UnknownStrategyException extends RuntimeException { + + public UnknownStrategyException(String value) { + super("Unknown strategy '" + value + "'. Use one of: " + labels()); + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java new file mode 100644 index 0000000..21dbd43 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/imports/ProductCsv.java @@ -0,0 +1,184 @@ +package com.amigoscode.batching.imports; + +import com.amigoscode.batching.product.ProductRow; +import java.io.IOException; +import java.io.Reader; +import java.io.UncheckedIOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/** + * Reads a product feed one row at a time, so a big file is never held in memory as a whole. + * + *
+ * sku,name,price,LON,MAN
+ * SKU-00001,"Mug, large",7.50,12,3
+ * 
+ * + * The first three columns are fixed. Every column after them is a warehouse, and its value is the + * stock in that warehouse. Fields may be quoted with double quotes, and a quote inside a quoted + * field is written twice (""). + */ +public final class ProductCsv implements Iterable { + + private final Reader reader; + private boolean used; + + private ProductCsv(Reader reader) { + this.reader = reader; + } + + public static ProductCsv read(Reader reader) { + return new ProductCsv(reader); + } + + /** Can be iterated once: the rows are read from the reader as you go. */ + @Override + public Iterator iterator() { + if (used) { + throw new IllegalStateException("A ProductCsv can only be read once"); + } + used = true; + Records records = new Records(reader); + List header = records.next(); + if (header == null || header.size() < 3 + || !header.get(0).equals("sku") || !header.get(1).equals("name") || !header.get(2).equals("price")) { + throw new BadCsvException(1, "the first line must be the header sku,name,price followed by optional warehouse codes"); + } + List warehouses = List.copyOf(header.subList(3, header.size())); + return new Iterator<>() { + + private List next = records.next(); + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public ProductRow next() { + if (next == null) { + throw new NoSuchElementException(); + } + ProductRow row = toRow(next, records.line(), header.size(), warehouses); + next = records.next(); + return row; + } + }; + } + + /** Reads the whole file into a list. Fine for a small file, or when you need every row at once. */ + public List toList() { + List rows = new ArrayList<>(); + forEach(rows::add); + return rows; + } + + private static ProductRow toRow(List fields, int line, int columns, List warehouses) { + if (fields.size() != columns) { + throw new BadCsvException(line, "expected " + columns + " fields, found " + fields.size()); + } + if (fields.get(0).isBlank()) { + throw new BadCsvException(line, "sku is empty"); + } + BigDecimal price; + try { + price = new BigDecimal(fields.get(2).trim()); + } catch (NumberFormatException e) { + throw new BadCsvException(line, "price is not a number: " + fields.get(2)); + } + Map stock = new LinkedHashMap<>(); + for (int i = 0; i < warehouses.size(); i++) { + String value = fields.get(3 + i).trim(); + try { + stock.put(warehouses.get(i), Integer.parseInt(value)); + } catch (NumberFormatException e) { + throw new BadCsvException(line, "stock for " + warehouses.get(i) + " is not a whole number: " + value); + } + } + return new ProductRow(fields.get(0).trim(), fields.get(1), price, stock); + } + + /** Splits the text into records of fields. Knows about quotes, nothing else. */ + private static final class Records { + + private final Reader reader; + private int linesRead; + private int recordStart; + + Records(Reader reader) { + this.reader = reader; + } + + /** The line the last record started on. */ + int line() { + return recordStart; + } + + /** The next record, or null at the end of the file. Empty lines are skipped. */ + List next() { + int c = read(); + while (c == '\n' || c == '\r') { + if (c == '\n') { + linesRead++; + } + c = read(); + } + if (c == -1) { + return null; + } + recordStart = linesRead + 1; + List fields = new ArrayList<>(); + StringBuilder field = new StringBuilder(); + boolean quoted = false; + while (true) { + if (quoted) { + if (c == -1) { + throw new BadCsvException(recordStart, "a quoted field is never closed"); + } + if (c == '"') { + int after = read(); + if (after != '"') { + quoted = false; + c = after; + continue; + } + field.append('"'); + } else { + if (c == '\n') { + linesRead++; + } + field.append((char) c); + } + } else if (c == '"' && field.isEmpty()) { + quoted = true; + } else if (c == ',') { + fields.add(field.toString()); + field.setLength(0); + } else if (c == '\n' || c == -1) { + if (c == '\n') { + linesRead++; + } + fields.add(field.toString()); + return fields; + } else if (c != '\r') { + field.append((char) c); + } + c = read(); + } + } + + private int read() { + try { + return reader.read(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java new file mode 100644 index 0000000..ee06ea6 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChange.java @@ -0,0 +1,59 @@ +package com.amigoscode.batching.price; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.math.BigDecimal; +import java.time.Instant; +import java.util.UUID; + +/** + * One line of the price history. The id is a UUID made in Java, so the database is not asked for + * one. + * + *

TODO Task 7: saving 1,000 of these sends 1,000 SELECTs nobody wrote. Find out who sends them + * and why, and make save() INSERT a new price change straight away. + */ +@Entity +@Table(name = "price_change") +public class PriceChange { + + @Id + private UUID id; + + private String sku; + + private BigDecimal price; + + private Instant changedAt; + + protected PriceChange() { + } + + public PriceChange(String sku, BigDecimal price, Instant changedAt) { + this.id = UUID.randomUUID(); + this.sku = sku; + this.price = price; + this.changedAt = changedAt; + } + + public UUID getId() { + return id; + } + + public String getSku() { + return sku; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public Instant getChangedAt() { + return changedAt; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java new file mode 100644 index 0000000..aa3701b --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceChangeRepository.java @@ -0,0 +1,7 @@ +package com.amigoscode.batching.price; + +import java.util.UUID; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PriceChangeRepository extends JpaRepository { +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java new file mode 100644 index 0000000..c979835 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/price/PriceHistory.java @@ -0,0 +1,28 @@ +package com.amigoscode.batching.price; + +import com.amigoscode.batching.product.ProductRow; +import java.time.Instant; +import java.util.List; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Writes one price change per row of the feed, all in one transaction. */ +@Service +public class PriceHistory { + + private final PriceChangeRepository priceChanges; + + public PriceHistory(PriceChangeRepository priceChanges) { + this.priceChanges = priceChanges; + } + + @Transactional + public int record(List rows) { + Instant now = Instant.now(); + List changes = rows.stream() + .map(row -> new PriceChange(row.sku(), row.price(), now)) + .toList(); + priceChanges.saveAll(changes); + return changes.size(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java new file mode 100644 index 0000000..345374e --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/JdbcProductImporter.java @@ -0,0 +1,79 @@ +package com.amigoscode.batching.product; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.postgresql.PGConnection; +import org.postgresql.copy.CopyIn; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Imports products without JPA: no entities, no persistence context, no cascades. The id comes from + * the column's default, and stock levels are not imported at all. + */ +@Service +public class JdbcProductImporter { + + private static final String INSERT = "insert into product (sku, name, price) values (?, ?, ?)"; + private static final String COPY = "copy product (sku, name, price) from stdin with (format csv)"; + + private final JdbcTemplate jdbc; + private final int batchSize; + + public JdbcProductImporter(JdbcTemplate jdbc, + @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) { + this.jdbc = jdbc; + this.batchSize = batchSize; + } + + /** + * TODO Task 8: no Hibernate here, and still one round trip per row. Send the rows in batches of + * batchSize, in one transaction. + */ + @Transactional + public int batchInsert(Iterable rows) { + int count = 0; + for (ProductRow row : rows) { + jdbc.update(INSERT, row.sku(), row.name(), row.price()); + count++; + } + return count; + } + + /** + * COPY: one statement, and the rows stream after it as CSV text. + * + *

TODO Task 8: fine for the demo's product names. Try a name with a comma in it. + */ + @Transactional + public long copy(Iterable rows) { + return jdbc.execute((ConnectionCallback) connection -> { + CopyIn copy = connection.unwrap(PGConnection.class).getCopyAPI().copyIn(COPY); + try { + for (ProductRow row : rows) { + byte[] line = (row.sku() + "," + row.name() + "," + row.price().toPlainString() + "\n") + .getBytes(StandardCharsets.UTF_8); + copy.writeToCopy(line, 0, line.length); + } + return copy.endCopy(); + } finally { + if (copy.isActive()) { + cancel(copy); + } + } + }); + } + + private static void cancel(CopyIn copy) { + try { + copy.cancelCopy(); + } catch (SQLException ignored) { + // The COPY already failed. That first error is the one worth reporting. + } + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java new file mode 100644 index 0000000..3d9a749 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/Product.java @@ -0,0 +1,91 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +@Entity +@Table(name = "product") +public class Product { + + /** + * Postgres makes the id while it runs the INSERT (the column is GENERATED BY DEFAULT AS IDENTITY, + * see schema.sql). + * + *

TODO Task 2: application.properties already asks Hibernate for batches of 50, and nothing is + * batched. Find out why, then let the ids come from a sequence instead. + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String sku; + + private String name; + + private BigDecimal price; + + @OneToMany(mappedBy = "product", cascade = CascadeType.ALL) + private List stockLevels = new ArrayList<>(); + + protected Product() { + } + + public Product(String sku, String name, BigDecimal price) { + this.sku = sku; + this.name = name; + this.price = price; + } + + /** A new product with one stock level per warehouse in the row. */ + public static Product from(ProductRow row) { + Product product = new Product(row.sku(), row.name(), row.price()); + new TreeMap<>(row.stock()).forEach(product::addStock); + return product; + } + + public void addStock(String warehouse, int quantity) { + stockLevels.add(new StockLevel(this, warehouse, quantity)); + } + + /** Takes the new price and the new stock per warehouse from the feed. */ + public void update(ProductRow row) { + this.price = row.price(); + Map stock = row.stock(); + for (StockLevel level : stockLevels) { + Integer quantity = stock.get(level.getWarehouse()); + if (quantity != null) { + level.setQuantity(quantity); + } + } + } + + public Long getId() { + return id; + } + + public String getSku() { + return sku; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public List getStockLevels() { + return stockLevels; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java new file mode 100644 index 0000000..06da2af --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductImporter.java @@ -0,0 +1,78 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Imports the supplier's feed with JPA. */ +@Service +public class ProductImporter { + + /** Postgres accepts at most 32,767 bind parameters in one statement, so a long IN list is split. */ + private static final int SKUS_PER_QUERY = 1_000; + + private final ProductRepository products; + private final EntityManager entityManager; + private final int batchSize; + + public ProductImporter(ProductRepository products, EntityManager entityManager, + @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:50}") int batchSize) { + this.products = products; + this.entityManager = entityManager; + this.batchSize = batchSize; + } + + /** + * The reference. Not @Transactional, so every save() is its own transaction: one INSERT and one + * COMMIT per row. Leave this one as it is, so you can always compare against it. + */ + public int importOneByOne(Iterable rows) { + int count = 0; + for (ProductRow row : rows) { + products.save(Product.from(row)); + count++; + } + return count; + } + + /** + * The whole file in one transaction, with saveAll. + * + *

TODO Task 6: every product saved here stays in the persistence context until the transaction + * ends. Keep at most batchSize of them in memory at any time, without breaking the batches and + * without splitting the import into several transactions. + */ + @Transactional + public int importBatched(Iterable rows) { + List all = new ArrayList<>(); + for (ProductRow row : rows) { + all.add(Product.from(row)); + } + products.saveAll(all); + return all.size(); + } + + /** The next day's feed: same SKUs, new prices and new stock. Returns how many products changed. */ + @Transactional + public int updateAll(List rows) { + Map bySku = new LinkedHashMap<>(); + rows.forEach(row -> bySku.put(row.sku(), row)); + List skus = new ArrayList<>(bySku.keySet()); + int updated = 0; + for (int from = 0; from < skus.size(); from += SKUS_PER_QUERY) { + List page = skus.subList(from, Math.min(from + SKUS_PER_QUERY, skus.size())); + for (Product product : products.findWithStockLevelsBySkuIn(page)) { + product.update(bySku.get(product.getSku())); + updated++; + } + } + // No save() needed: every product is managed, so Hibernate sends an UPDATE for each one it + // finds changed when the transaction commits. + return updated; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java new file mode 100644 index 0000000..abb1615 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRepository.java @@ -0,0 +1,13 @@ +package com.amigoscode.batching.product; + +import java.util.Collection; +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 ProductRepository extends JpaRepository { + + @Query("select distinct p from Product p left join fetch p.stockLevels where p.sku in :skus") + List findWithStockLevelsBySkuIn(@Param("skus") Collection skus); +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java new file mode 100644 index 0000000..b936374 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/ProductRow.java @@ -0,0 +1,16 @@ +package com.amigoscode.batching.product; + +import java.math.BigDecimal; +import java.util.Map; + +/** One line of the supplier's feed. {@code stock} is the quantity per warehouse code, and may be empty. */ +public record ProductRow(String sku, String name, BigDecimal price, Map stock) { + + public ProductRow { + stock = Map.copyOf(stock); + } + + public ProductRow(String sku, String name, BigDecimal price) { + this(sku, name, price, Map.of()); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java new file mode 100644 index 0000000..d28f423 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/java/com/amigoscode/batching/product/StockLevel.java @@ -0,0 +1,54 @@ +package com.amigoscode.batching.product; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +/** How many of a product one warehouse holds. Saved together with its product (cascade). */ +@Entity +@Table(name = "stock_level") +public class StockLevel { + + // TODO Task 5: same problem as Product. + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id") + private Product product; + + private String warehouse; + + private int quantity; + + protected StockLevel() { + } + + StockLevel(Product product, String warehouse, int quantity) { + this.product = product; + this.warehouse = warehouse; + this.quantity = quantity; + } + + public Long getId() { + return id; + } + + public String getWarehouse() { + return warehouse; + } + + public int getQuantity() { + return quantity; + } + + void setQuantity(int quantity) { + this.quantity = quantity; + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties new file mode 100644 index 0000000..f7a87d7 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/application.properties @@ -0,0 +1,21 @@ +spring.application.name=batch-writes + +# Postgres from compose.yaml. Port 5455 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5455/batching} +spring.datasource.username=${DB_USER:batching} +spring.datasource.password=${DB_PASSWORD:batching} + +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# schema.sql drops and creates the tables on every start, so every run begins empty. +spring.sql.init.mode=always + +# Send INSERTs and UPDATEs in JDBC batches of 50 statements. (Or so it says: see Task 1.) +spring.jpa.properties.hibernate.jdbc.batch_size=50 + +# Counts the entities in the persistence context at every flush. ./demo and the tests read it. +spring.jpa.properties.hibernate.session_factory.interceptor=com.amigoscode.batching.db.ManagedEntities + +# Uncomment to see every SQL statement (or run ./demo --sql). +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql new file mode 100644 index 0000000..8df2b32 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/main/resources/schema.sql @@ -0,0 +1,33 @@ +-- Runs on every start, so every run begins with empty tables. + +-- Counts every statement Postgres executes. ./demo and ./inspect read it. It needs +-- shared_preload_libraries=pg_stat_statements, which compose.yaml sets. +create extension if not exists pg_stat_statements; + +drop table if exists stock_level, product, price_change; +drop sequence if exists product_seq, stock_level_seq; + +-- Postgres makes each id while it runs the INSERT. +create table product ( + id bigint primary key generated by default as identity, + sku text not null unique, + name text not null, + price numeric(10,2) not null check (price >= 0) +); + +create table stock_level ( + id bigint primary key generated by default as identity, + product_id bigint not null references product (id), + warehouse text not null, + quantity int not null check (quantity >= 0) +); + +create index stock_level_product_id on stock_level (product_id); + +-- The id is a UUID made in Java (see PriceChange). +create table price_change ( + id uuid primary key, + sku text not null, + price numeric(10,2) not null, + changed_at timestamptz not null +); diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java new file mode 100644 index 0000000..50781ec --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/Check.java @@ -0,0 +1,116 @@ +package com.amigoscode.batching; + +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. Task 3 is an inspection task: you answer questions, no code. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: the CSV format and the HTTP contract (passes from the start, must stay green)"); + TASKS.put("1", "Task 1: See 10,000 round trips"); + TASKS.put("2", "Task 2: Let Hibernate batch: SEQUENCE instead of IDENTITY"); + TASKS.put("4", "Task 4: Multi-row INSERTs: reWriteBatchedInserts"); + TASKS.put("5", "Task 5: Parents and children: order_inserts and order_updates"); + TASKS.put("6", "Task 6: Flat memory: flush and clear"); + TASKS.put("7", "Task 7: Ids made in Java: no SELECT before every INSERT"); + TASKS.put("8", "Task 8: Leave JPA: JdbcTemplate and COPY"); + } + + 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/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java new file mode 100644 index 0000000..6dca681 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ImportControllerTest.java @@ -0,0 +1,95 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amigoscode.batching.imports.ImportController; +import com.amigoscode.batching.imports.ImportService; +import com.amigoscode.batching.imports.ImportStrategy; +import com.amigoscode.batching.product.ProductRow; +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; +import org.springframework.dao.DataIntegrityViolationException; +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, ImportService is a stub. They + * pass from the start and must keep passing whatever you change behind the controller. + */ +@Tag("baseline") +class ImportControllerTest { + + private static final String CSV = "sku,name,price\nSKU-1,Mug,7.50\nSKU-2,Kettle,24.00\n"; + + @Test + @DisplayName("HTTP: POST /api/imports/products reads the CSV row by row and returns how many rows were imported") + void importReturnsTheRowCount() throws Exception { + List received = new ArrayList<>(); + ImportStrategy[] strategy = new ImportStrategy[1]; + + api((chosen, rows) -> { + strategy[0] = chosen; + rows.forEach(received::add); + return received.size(); + }).perform(post("/api/imports/products?strategy=copy").contentType("text/csv").content(CSV)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.strategy").value("copy")) + .andExpect(jsonPath("$.rows").value(2)); + + assertThat(strategy[0]).isEqualTo(ImportStrategy.COPY); + assertThat(received).extracting(ProductRow::sku).containsExactly("SKU-1", "SKU-2"); + } + + @Test + @DisplayName("HTTP: an unknown strategy returns 400 UNKNOWN_STRATEGY") + void unknownStrategy() throws Exception { + api((chosen, rows) -> 0).perform(post("/api/imports/products?strategy=faster").contentType("text/csv").content(CSV)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("UNKNOWN_STRATEGY")); + } + + @Test + @DisplayName("HTTP: a row that cannot be read returns 400 BAD_CSV with its line number") + void badRow() throws Exception { + api((chosen, rows) -> { + rows.forEach(row -> { }); + return 0; + }).perform(post("/api/imports/products").contentType("text/csv").content(CSV + "SKU-3,Lamp,cheap\n")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("BAD_CSV")) + .andExpect(jsonPath("$.line").value(4)); + } + + @Test + @DisplayName("HTTP: a row the database refuses returns 422 IMPORT_REJECTED") + void rejectedRow() throws Exception { + api((chosen, rows) -> { + throw new DataIntegrityViolationException("new row violates check constraint \"product_price_check\""); + }).perform(post("/api/imports/products").contentType("text/csv").content(CSV)) + .andExpect(status().isUnprocessableContent()) + .andExpect(jsonPath("$.code").value("IMPORT_REJECTED")); + } + + private interface Importer { + long run(ImportStrategy strategy, Iterable rows); + } + + /** The controller wired to an ImportService whose importProducts does whatever the test says. */ + private static MockMvc api(Importer importer) { + ImportService stub = new ImportService(null, null, null) { + @Override + public long importProducts(ImportStrategy strategy, Iterable rows) { + return importer.run(strategy, rows); + } + }; + return MockMvcBuilders.standaloneSetup(new ImportController(stub)) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java new file mode 100644 index 0000000..ae14e93 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/JdbcImportIT.java @@ -0,0 +1,88 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlCall; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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; + +/** No JPA: JdbcTemplate.batchUpdate and Postgres COPY. */ +@Tag("task8") +class JdbcImportIT extends IntegrationTest { + + /** A comma, double quotes, a backslash, a line break and a tab: everything that breaks hand-made CSV. */ + private static final String AWKWARD_NAME = "Mug, \"large\"\\0.5 l\nsecond line\tand a tab"; + + @Test + @DisplayName("JdbcTemplate: 2,000 products in 40 round trips, batches of 50") + void jdbcTemplateSendsBatches() { + Recording recording = record(() -> jdbcImporter.batchInsert(Rows.products(2_000))); + + assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("JdbcTemplate: a name with commas, quotes, a backslash and a line break is stored exactly as sent") + void jdbcTemplateStoresAwkwardNames() { + jdbcImporter.batchInsert(List.of(new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")))); + + assertThat(jdbc.queryForObject("select name from product", String.class)).isEqualTo(AWKWARD_NAME); + } + + @Test + @DisplayName("COPY: 2,000 products in one statement") + void copyIsOneStatement() { + Recording recording = record(() -> jdbcImporter.copy(Rows.products(2_000))); + + assertThat(recording.roundTrips()).as("round trips\n" + recording.describe()).isEqualTo(1); + assertThat(recording.calls().getFirst().kind()).as("kind of round trip").isEqualTo(SqlCall.Kind.COPY); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("COPY: a name with commas, quotes, a backslash and a line break is stored exactly as sent") + void copyStoresAwkwardNames() { + List rows = List.of( + new ProductRow("SKU-1", AWKWARD_NAME, new BigDecimal("7.50")), + new ProductRow("SKU-2", "Plain name", new BigDecimal("1.00"))); + + try { + jdbcImporter.copy(rows); + } catch (RuntimeException e) { + throw new AssertionError("COPY refused the rows: " + rootMessage(e), e); + } + + assertThat(jdbc.queryForList("select name from product order by sku", String.class)) + .containsExactly(AWKWARD_NAME, "Plain name"); + } + + @Test + @DisplayName("COPY: one bad row (a negative price) and nothing is stored, not even the rows before it") + void oneBadRowStopsTheWholeCopy() { + List rows = new ArrayList<>(Rows.products(2_000)); + rows.set(1_500, new ProductRow("SKU-1501", "Product 1501", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> jdbcImporter.copy(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products stored").isZero(); + } + + private static String rootMessage(Throwable e) { + Throwable root = e; + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + } + return root.getMessage(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java new file mode 100644 index 0000000..ad70242 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/OneByOneIT.java @@ -0,0 +1,42 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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 1. These tests pass on purpose: they pin down the problem so you can see what the fixes change. */ +@Tag("task1") +class OneByOneIT extends IntegrationTest { + + @Test + @DisplayName("One by one: 500 rows are 500 INSERTs, each in its own round trip and its own transaction (this documents the problem)") + void everyRowIsItsOwnRoundTripAndTransaction() { + Recording recording = record(() -> productImporter.importOneByOne(Rows.products(500))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(500); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(1); + assertThat(recording.commits()).as("commits").isEqualTo(500); + assertThat(count("product")).as("products stored").isEqualTo(500); + } + + @Test + @DisplayName("One by one: a bad row in the middle leaves every row before it in the database (this documents the problem)") + void aBadRowLeavesHalfAnImport() { + List rows = new ArrayList<>(Rows.products(100)); + rows.set(60, new ProductRow("SKU-61", "Product 61", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> productImporter.importOneByOne(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products left behind by a failed import").isEqualTo(60); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java new file mode 100644 index 0000000..cee1bca --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ParentsAndChildrenIT.java @@ -0,0 +1,68 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** 500 products with 3 stock levels each: 500 parents and 1,500 children saved in one go. */ +@Tag("task5") +class ParentsAndChildrenIT extends IntegrationTest { + + @Test + @DisplayName("Insert: 500 products and 1,500 stock levels go in full batches: 10 product batches and 30 stock level batches") + void insertsAreSortedIntoFullBatches() { + Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + String sent = "\n" + recording.describe(); + assertThat(recording.roundTrips("insert into product")).as("product INSERT round trips" + sent).isLessThanOrEqualTo(10); + assertThat(recording.roundTrips("insert into stock_level")).as("stock level INSERT round trips" + sent).isLessThanOrEqualTo(30); + } + + @Test + @DisplayName("Insert: stock levels get their ids from a sequence too, at most 31 nextval calls for 1,500 of them") + void stockLevelIdsComeFromASequence() { + Recording recording = record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + assertThat(recording.roundTrips("select nextval('stock_level_seq')")) + .as("nextval('stock_level_seq') round trips\n" + recording.describe()).isBetween(1, 31); + } + + @Test + @DisplayName("Update: a new price and new stock for 500 products takes at most 40 UPDATE round trips, not 1,000") + void updatesAreSortedIntoFullBatches() { + productImporter.importBatched(Rows.productsWithStock(500, 0)); + + Recording recording = record(() -> productImporter.updateAll(Rows.productsWithStock(500, 1))); + + assertThat(recording.roundTrips("update")).as("UPDATE round trips\n" + recording.describe()).isLessThanOrEqualTo(40); + assertThat(stockLevelsMatching(1)).as("stock levels that now hold the next day's quantity").isEqualTo(1_500); + // Every price went up by 1.00: 1.01 + ... + 6.00 is 1,752.50, plus 500 x 1.00. + assertThat(jdbc.queryForObject("select sum(price) from product", java.math.BigDecimal.class)) + .as("sum of the new prices").isEqualByComparingTo("2252.50"); + } + + @Test + @DisplayName("Insert: every stock level is stored and points to its own product") + void everyStockLevelBelongsToItsProduct() { + productImporter.importBatched(Rows.productsWithStock(500, 0)); + + assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500); + assertThat(stockLevelsMatching(0)).as("stock levels whose quantity matches their own product's row").isEqualTo(1_500); + } + + /** Stock levels whose quantity is what Rows.productsWithStock(.., day) gave their product. */ + private long stockLevelsMatching(int day) { + return jdbc.queryForObject(""" + select count(*) + from stock_level s + join product p on p.id = s.product_id + where s.quantity = (cast(substring(p.sku from 5) as int) + + ? * case s.warehouse when 'GLA' then 1 when 'LON' then 2 else 3 end) % 10 + """, Long.class, day); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java new file mode 100644 index 0000000..65f3115 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PersistenceContextIT.java @@ -0,0 +1,63 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.ProductRow; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +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; + +/** + * ManagedEntities counts the entities in the persistence context every time Hibernate flushes. + * Every managed entity stays in memory, with a copy of its values for dirty checking, until the + * transaction ends or the persistence context is cleared. + */ +@Tag("task6") +class PersistenceContextIT extends IntegrationTest { + + @Test + @DisplayName("Memory: importing 2,000 products never holds more than 50 entities in the persistence context") + void productsAreNotKeptInMemory() { + record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("Memory: with stock levels, never more than 200 entities (50 products and their 150 stock levels)") + void productsWithStockAreNotKeptInMemory() { + record(() -> productImporter.importBatched(Rows.productsWithStock(500, 0))); + + assertThat(ManagedEntities.peak()).as("most entities in the persistence context at one flush").isLessThanOrEqualTo(200); + assertThat(count("stock_level")).as("stock levels stored").isEqualTo(1_500); + } + + @Test + @DisplayName("Memory: clearing every 50 rows keeps the batches full: still 40 INSERT batches of 50 for 2,000 products") + void clearingKeepsTheBatchesFull() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + } + + @Test + @DisplayName("Memory: flush is not commit: a bad row near the end still rolls back the whole import") + void flushIsNotCommit() { + List rows = new ArrayList<>(Rows.products(2_000)); + rows.set(1_900, new ProductRow("SKU-1901", "Product 1901", new BigDecimal("-1.00"))); + + assertThatThrownBy(() -> productImporter.importBatched(rows)).as("a negative price is refused by the database"); + + assertThat(count("product")).as("products left behind by a failed import").isZero(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java new file mode 100644 index 0000000..82a6e87 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/PriceHistoryIT.java @@ -0,0 +1,64 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.price.PriceChange; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import java.math.BigDecimal; +import java.time.Instant; +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.beans.factory.annotation.Autowired; +import org.springframework.transaction.support.TransactionTemplate; + +/** PriceChange ids are UUIDs made in Java, so the id is never null, not even before the first save. */ +@Tag("task7") +class PriceHistoryIT extends IntegrationTest { + + @Autowired + private TransactionTemplate transaction; + + @Test + @DisplayName("Assigned ids: saving 1,000 price changes sends no SELECT, only 20 INSERT batches") + void noSelectBeforeEveryInsert() { + Recording recording = record(() -> priceHistory.record(Rows.products(1_000))); + + String sent = "\n" + recording.describe(); + assertThat(recording.roundTrips("select")).as("SELECT round trips" + sent).isZero(); + assertThat(recording.roundTrips("insert into price_change")).as("INSERT round trips" + sent).isEqualTo(20); + assertThat(count("price_change")).as("price changes stored").isEqualTo(1_000); + } + + @Test + @DisplayName("Assigned ids: saveAll() returns the objects you gave it (persist), not copies of them (merge)") + void saveAllPersistsTheSameObjects() { + List changes = List.of( + new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()), + new PriceChange("SKU-2", new BigDecimal("2.00"), Instant.now())); + + List saved = transaction.execute(status -> priceChanges.saveAll(changes)); + + assertThat(saved).as("what saveAll returned").hasSize(2); + assertThat(saved.get(0)).as("the first object saveAll returned").isSameAs(changes.get(0)); + assertThat(saved.get(1)).as("the second object saveAll returned").isSameAs(changes.get(1)); + } + + @Test + @DisplayName("Assigned ids: a price change loaded from the database and saved again is updated, not inserted a second time") + void aLoadedPriceChangeIsUpdated() { + PriceChange original = new PriceChange("SKU-1", new BigDecimal("1.00"), Instant.now()); + transaction.executeWithoutResult(status -> priceChanges.save(original)); + + PriceChange loaded = priceChanges.findById(original.getId()).orElseThrow(); + loaded.setPrice(new BigDecimal("1.50")); + transaction.executeWithoutResult(status -> priceChanges.save(loaded)); + + assertThat(count("price_change")).as("price change rows").isEqualTo(1); + assertThat(jdbc.queryForObject("select price from price_change", BigDecimal.class)).as("the stored price") + .isEqualByComparingTo("1.50"); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java new file mode 100644 index 0000000..6014c02 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/ProductCsvTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.batching.imports.BadCsvException; +import com.amigoscode.batching.imports.ProductCsv; +import com.amigoscode.batching.product.ProductRow; +import java.io.StringReader; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Unit tests: no Spring, no database. The feed format, which none of the tasks change. */ +@Tag("baseline") +class ProductCsvTest { + + @Test + @DisplayName("CSV: quoted fields keep their commas, quotes and line breaks") + void quotedFields() { + List rows = read(""" + sku,name,price + SKU-1,"Mug, ""large"" + second line",7.50 + SKU-2,Plain,1 + """); + + assertThat(rows).extracting(ProductRow::name).containsExactly("Mug, \"large\"\nsecond line", "Plain"); + assertThat(rows.get(0).price()).isEqualByComparingTo("7.50"); + } + + @Test + @DisplayName("CSV: every column after price is a warehouse, and its value is the stock there") + void warehouseColumns() { + List rows = read(""" + sku,name,price,LON,MAN + SKU-1,Mug,7.50,12,3 + """); + + assertThat(rows.getFirst().stock()).isEqualTo(Map.of("LON", 12, "MAN", 3)); + } + + @Test + @DisplayName("CSV: a price that is not a number is rejected with its line number") + void badPrice() { + assertThatThrownBy(() -> read(""" + sku,name,price + SKU-1,Mug,7.50 + SKU-2,Kettle,cheap + """)) + .isInstanceOf(BadCsvException.class) + .hasMessageContaining("Line 3"); + } + + private static List read(String csv) { + return ProductCsv.read(new StringReader(csv)).toList(); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java new file mode 100644 index 0000000..3be1280 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/RewriteIT.java @@ -0,0 +1,54 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import com.amigoscode.batching.support.ServerSide; +import java.math.BigDecimal; +import java.sql.Connection; +import javax.sql.DataSource; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.postgresql.core.BaseConnection; +import org.springframework.beans.factory.annotation.Autowired; + +@Tag("task4") +class RewriteIT extends IntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + @DisplayName("Driver: the connections of the pool have reWriteBatchedInserts switched on") + void theDriverRewritesBatches() throws Exception { + try (Connection connection = dataSource.getConnection()) { + boolean rewrite = connection.unwrap(BaseConnection.class).getQueryExecutor().isReWriteBatchedInsertsEnabled(); + + assertThat(rewrite).as("reWriteBatchedInserts, as the Postgres driver sees it").isTrue(); + } + } + + @Test + @DisplayName("Postgres: 2,000 products arrive as multi-row INSERTs, at most 200 INSERT executions instead of 2,000") + void postgresExecutesMultiRowInserts() { + ServerSide.Executed executed = onTheServer(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(executed.rows("insert into product")).as("rows inserted\n" + executed.describe()).isEqualTo(2_000); + assertThat(executed.executions("insert into product")).as("INSERT statements Postgres executed\n" + executed.describe()) + .isLessThanOrEqualTo(200); + } + + @Test + @DisplayName("Postgres: every row still arrives exactly once (2,000 rows, and the prices add up)") + void everyRowArrivesOnce() { + productImporter.importBatched(Rows.products(2_000)); + + assertThat(count("product")).as("products stored").isEqualTo(2_000); + assertThat(jdbc.queryForObject("select count(distinct sku) from product", Long.class)).as("distinct SKUs").isEqualTo(2_000); + // 1.01 + 1.02 + ... + 21.00 + assertThat(jdbc.queryForObject("select sum(price) from product", BigDecimal.class)).as("sum of the prices") + .isEqualByComparingTo("22010.00"); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java new file mode 100644 index 0000000..bfc5189 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/SequenceIdsIT.java @@ -0,0 +1,68 @@ +package com.amigoscode.batching; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.product.Product; +import com.amigoscode.batching.support.IntegrationTest; +import com.amigoscode.batching.support.Rows; +import jakarta.persistence.EntityManagerFactory; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.generator.Generator; +import org.hibernate.id.enhanced.SequenceStyleGenerator; +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; + +@Tag("task2") +class SequenceIdsIT extends IntegrationTest { + + @Autowired + private EntityManagerFactory entityManagerFactory; + + @Test + @DisplayName("Batched: 2,000 products are sent as 40 INSERT batches of 50, not 2,000 single INSERTs") + void insertsAreSentInBatches() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("insert into product")).as("INSERT round trips\n" + recording.describe()).isEqualTo(40); + assertThat(recording.largestBatch("insert into product")).as("most rows in one round trip").isEqualTo(50); + assertThat(count("product")).as("products stored").isEqualTo(2_000); + } + + @Test + @DisplayName("Batched: the ids come from a sequence, 50 at a time: at most 41 nextval calls for 2,000 products") + void idsComeFromTheSequenceFiftyAtATime() { + Recording recording = record(() -> productImporter.importBatched(Rows.products(2_000))); + + assertThat(recording.roundTrips("select nextval")).as("nextval round trips\n" + recording.describe()) + .isBetween(1, 41); + } + + @Test + @DisplayName("Mapping: Product uses a SEQUENCE generator whose allocationSize equals the sequence's INCREMENT BY") + void allocationSizeMatchesTheSequence() { + Generator generator = entityManagerFactory.unwrap(SessionFactoryImplementor.class) + .getMappingMetamodel().getEntityDescriptor(Product.class).getGenerator(); + + assertThat(generator).as("the id generator of Product").isInstanceOf(SequenceStyleGenerator.class); + SequenceStyleGenerator sequence = (SequenceStyleGenerator) generator; + String name = sequence.getDatabaseStructure().getPhysicalName().getObjectName().getText(); + Long incrementBy = jdbc.queryForObject("select increment_by from pg_sequences where sequencename = ?", Long.class, name); + assertThat(sequence.getOptimizer().getIncrementSize()).as("allocationSize of " + name) + .isGreaterThan(1) + .isEqualTo(incrementBy.intValue()); + } + + @Test + @DisplayName("Ids: two imports with a plain SQL INSERT in between never hand out the same id twice") + void idsNeverClash() { + productImporter.importBatched(Rows.products(1_000, "A-")); + jdbc.update("insert into product (sku, name, price) values ('PLAIN-1', 'Inserted with plain SQL', 1.00)"); + productImporter.importBatched(Rows.products(1_000, "B-")); + + assertThat(jdbc.queryForObject("select count(distinct id) from product", Long.class)) + .as("distinct ids for 2,001 products").isEqualTo(2_001); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java new file mode 100644 index 0000000..3435396 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/DriverOptions.java @@ -0,0 +1,40 @@ +package com.amigoscode.batching.support; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.Properties; + +/** + * The tests talk to a Postgres started by Testcontainers, on its own URL. Driver options you add to + * spring.datasource.url in application.properties (everything after the "?") are copied onto that + * URL, so they apply in the tests exactly as they do in ./demo. + */ +final class DriverOptions { + + /** "&reWriteBatchedInserts=true", or "" when the URL in application.properties has no options. */ + static String fromApplicationProperties() { + Properties properties = new Properties(); + try (InputStream in = DriverOptions.class.getResourceAsStream("/application.properties")) { + if (in == null) { + return ""; + } + properties.load(in); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + String url = properties.getProperty("spring.datasource.url", ""); + int query = url.indexOf('?'); + if (query < 0) { + return ""; + } + String options = url.substring(query + 1); + if (options.endsWith("}")) { + options = options.substring(0, options.length() - 1); + } + return options.isBlank() ? "" : "&" + options; + } + + private DriverOptions() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java new file mode 100644 index 0000000..9fa6df2 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/IntegrationTest.java @@ -0,0 +1,86 @@ +package com.amigoscode.batching.support; + +import com.amigoscode.batching.db.ManagedEntities; +import com.amigoscode.batching.db.Recording; +import com.amigoscode.batching.db.SqlRecorder; +import com.amigoscode.batching.price.PriceChangeRepository; +import com.amigoscode.batching.price.PriceHistory; +import com.amigoscode.batching.product.JdbcProductImporter; +import com.amigoscode.batching.product.ProductImporter; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +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 how many round trips an import makes is decided + * by Hibernate, the mapping and the JDBC driver together, and no mock can tell you that. One + * container is shared by every test class. + * + *

The tests never measure time. They count: round trips to the database (SqlRecorder), statements + * Postgres executed (pg_stat_statements), entities in the persistence context (ManagedEntities) and + * rows in the tables. + */ +@SpringBootTest(properties = "spring.main.banner-mode=off") +public abstract class IntegrationTest { + + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine") + .withCommand("postgres", "-c", "fsync=off", "-c", "shared_preload_libraries=pg_stat_statements"); + + static { + POSTGRES.start(); + } + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", () -> POSTGRES.getJdbcUrl() + DriverOptions.fromApplicationProperties()); + registry.add("spring.datasource.username", POSTGRES::getUsername); + registry.add("spring.datasource.password", POSTGRES::getPassword); + } + + @Autowired + protected ProductImporter productImporter; + + @Autowired + protected JdbcProductImporter jdbcImporter; + + @Autowired + protected PriceHistory priceHistory; + + @Autowired + protected PriceChangeRepository priceChanges; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyTables() { + jdbc.execute("truncate table stock_level, product, price_change"); + } + + /** Runs the work and returns every round trip it made to Postgres. */ + protected Recording record(Runnable work) { + ManagedEntities.reset(); + SqlRecorder.start(); + try { + work.run(); + } catch (RuntimeException e) { + SqlRecorder.stop(); + throw e; + } + return SqlRecorder.stop(); + } + + /** Runs the work and returns what Postgres itself executed while it ran (pg_stat_statements). */ + protected ServerSide.Executed onTheServer(Runnable work) { + return ServerSide.during(jdbc, work); + } + + protected long count(String table) { + return jdbc.queryForObject("select count(*) from " + table, Long.class); + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java new file mode 100644 index 0000000..8153d92 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/Rows.java @@ -0,0 +1,42 @@ +package com.amigoscode.batching.support; + +import com.amigoscode.batching.product.ProductRow; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** Rows of a feed, made up in the test. */ +public final class Rows { + + public static List products(int count) { + return products(count, "SKU-"); + } + + /** Different prefixes give different SKUs, so two imports in one test do not clash. */ + public static List products(int count, String skuPrefix) { + List rows = new ArrayList<>(count); + for (int i = 1; i <= count; i++) { + rows.add(new ProductRow(skuPrefix + i, "Product " + i, price(i))); + } + return rows; + } + + /** Every product with stock in three warehouses. {@code day} changes the price and the stock. */ + public static List productsWithStock(int count, int day) { + List rows = new ArrayList<>(count); + for (int i = 1; i <= count; i++) { + rows.add(new ProductRow("SKU-" + i, "Product " + i, price(i).add(BigDecimal.valueOf(day)), + Map.of("GLA", (i + day) % 10, "LON", (i + 2 * day) % 10, "MAN", (i + 3 * day) % 10))); + } + return rows; + } + + /** 1.00, 1.01, ... so the total of the prices tells you whether every row arrived once. */ + public static BigDecimal price(int i) { + return BigDecimal.valueOf(100 + i, 2); + } + + private Rows() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java new file mode 100644 index 0000000..83831bd --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/start/src/test/java/com/amigoscode/batching/support/ServerSide.java @@ -0,0 +1,53 @@ +package com.amigoscode.batching.support; + +import java.util.List; +import java.util.Locale; +import org.springframework.jdbc.core.JdbcTemplate; + +/** What Postgres itself executed, read from pg_stat_statements. */ +public final class ServerSide { + + /** One statement as Postgres normalised it, how many times it ran, and how many rows it touched. */ + public record Statement(String query, long executions, long rows) { + } + + public record Executed(List statements) { + + /** How many times Postgres ran a statement that starts with the prefix, for example "insert into product". */ + public long executions(String prefix) { + return matching(prefix).stream().mapToLong(Statement::executions).sum(); + } + + public long rows(String prefix) { + return matching(prefix).stream().mapToLong(Statement::rows).sum(); + } + + private List matching(String prefix) { + return statements.stream() + .filter(statement -> statement.query().toLowerCase(Locale.ROOT).startsWith(prefix.toLowerCase(Locale.ROOT))) + .toList(); + } + + public String describe() { + StringBuilder text = new StringBuilder("Postgres executed:"); + statements.forEach(statement -> text.append(String.format("%n%,d x %s", statement.executions(), + statement.query().length() > 90 ? statement.query().substring(0, 90) + "..." : statement.query()))); + return text.toString(); + } + } + + static Executed during(JdbcTemplate jdbc, Runnable work) { + jdbc.execute("select pg_stat_statements_reset()"); + work.run(); + return new Executed(jdbc.query(""" + select regexp_replace(query, '\\s+', ' ', 'g') as query, calls, rows + from pg_stat_statements + where dbid = (select oid from pg_database where datname = current_database()) + and query !~* 'pg_stat_statements' + order by calls desc + """, (row, number) -> new Statement(row.getString(1), row.getLong(2), row.getLong(3)))); + } + + private ServerSide() { + } +} diff --git a/java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/16-batch-writes/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..82166a4 --- /dev/null +++ b/java/concepts/junior-mid/16-batch-writes/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/17-testing-with-a-real-database/INTERVIEW_TASKS.md b/java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md new file mode 100644 index 0000000..25d119c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/INTERVIEW_TASKS.md @@ -0,0 +1,265 @@ +# Interview Tasks — Testing With a Real Database + +> **In `start/`, `./check` FAILS on purpose: 9 of 24 checks pass.** Tasks 2, 4, 5, 6 and 7 turn the +> other 15 green. Tasks 1 and 3 have checks that pass from the start: they document how H2, +> Postgres and `@DataJpaTest` behave. Task 8 is an inspection task: you run things, look, and answer +> questions. + +Do the tasks in order. A green test only tells you something if it can go red. In every task you +first make your tests see the problem, then fix the code, then look at what your tests actually did. + +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 anything under `check/`. Do not rename `findTopRated`, +`findByShelf`, `subscribe`, `BookRepositoryTest` or `SubscriptionServiceTest`: the checks use those +names. Read "Two kinds of test in this project" in the [README](README.md) first: here the checks +judge your tests, not only your code. + +--- + +## Task 1: See It Break (10 min) + +**Story:** *The suite is green, CI is green, the release went out. On day one: the "top rated" page +shows a book with no reviews at number 1, audiobooks cannot be added, nobody can subscribe to the +newsletter, and shelves come back in a strange order. Before you change anything, find out why the +tests did not notice.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. How many tests pass? How many features work in + production? +2. Read the database table in the demo output. Which database did each test class use? Which test + used no database at all? +3. For each broken feature, find the test that is supposed to cover it. What does that test do, and + why is it green? +4. Open `catalogue/BookRepositoryTest`. Its `@DataJpaTest` turns Flyway off. Why? What builds the + tables instead? +5. `./check 1`. Each check runs the same SQL on H2 and on Postgres. Write down the three + differences. + +**Acceptance Criteria** (`./check 1`, already passing: these checks document the differences) +- [ ] You can say which database each of your test classes ran on +- [ ] You can name, for each of the four bugs, why the test was green +- [ ] You can explain why "H2 in PostgreSQL mode" is not Postgres + +**Hints:** +- Postgres sorts NULL as the largest value +- `SubscriptionServiceTest` never sends any SQL anywhere +- Where does the `CHECK` constraint on `book.format` live? Where does the H2 schema come from? + +--- + +## Task 2: Run the Repository Tests on Postgres (20 min) + +**Story:** *Make `BookRepositoryTest` run against the database production uses, with the schema +production uses. Then fix whatever it finds.* + +**Acceptance Criteria** (`./check 2`) +- [ ] Production: top rated lists the best rated books first, never an unrated one ahead of them +- [ ] Production: an `AUDIOBOOK` can be added +- [ ] `BookRepositoryTest` runs on PostgreSQL, not H2 +- [ ] Its schema comes from the Flyway migrations, not from Hibernate +- [ ] Your suite catches the top rated bug: with the `start/` query put back, a test fails +- [ ] Your suite catches the missing migration: with `AUDIOBOOK` rejected again, a test fails +- [ ] `./demo` shows your tests turn red before your fix and green after it + +**Hints:** +- Testcontainers starts a throwaway Postgres in Docker. Boot's `@ServiceConnection` on the container + field tells Spring where it is: no URL to write +- Remove the properties that turned Flyway off and told Hibernate to create the tables +- Make the tests red first, then fix the code: a query in `BookRepository` and a new migration file. + Never edit `V1`: it has already run in production + +--- + +## Task 3: Inspect Which Database Your Test Really Used (10 min) + +**Story:** *"The test was supposed to use Postgres" is a sentence people say after an incident. Prove +which database each test talks to, and find out what `@DataJpaTest` does on its own.* + +**Steps:** +1. `./inspect`. For each test class: which database, which URL, and where did its schema come from? +2. In `start/` as you received it, `BookRepositoryTest` had no URL at all, and + `application.properties` points at Postgres on port 5456. Yet it ran on H2. Who replaced it? +3. In `BookRepositoryTest`, comment out `@ServiceConnection` (keep the container) and run + `./inspect`. What happened, and what is the error? Put it back. +4. `./check 3`. Write down the three rules it documents. +5. Contexts: how many Spring contexts did your suite start? Which classes used which? + +**Acceptance Criteria** (`./check 3`, already passing: these checks document Spring Boot's behaviour) +- [ ] You can say when `@DataJpaTest` swaps your DataSource for an embedded database, and how to stop it +- [ ] You can explain the difference between `@ServiceConnection` and `@DynamicPropertySource` +- [ ] You can say what a `@DataJpaTest` loads, compared with a `@SpringBootTest` + +--- + +## Task 4: Replace the Fake Where It Hides the SQL (15 min) + +**Story:** *`subscribe` is one `INSERT ... ON CONFLICT`. H2 cannot run it, so someone tested the +service with a fake instead. The fake does what we believe the SQL does. Find out what it really +does.* + +**Acceptance Criteria** (`./check 4`) +- [ ] Production: `ann@example.com` then `Ann@Example.COM` gives one subscriber and + `ALREADY_SUBSCRIBED`, with no error +- [ ] Your suite catches the `ON CONFLICT` bug: with the `start/` SQL put back, a test fails +- [ ] `SubscriptionServiceTest` still tests the service's logic with the fake, with no Spring and no + database (already passing: keep it that way) + +**Hints:** +- A new `@DataJpaTest`, `SubscriberRepositoryTest`, on Postgres, calling `subscribe` directly +- Read the unique index in `V1__create_catalogue.sql`. `ON CONFLICT (...)` must name exactly what an + index is built on +- Which tests in `SubscriptionServiceTest` are about the service, and which pretend to be about SQL? + +--- + +## Task 5: One Container, One Context per Kind of Test (20 min) + +**Story:** *The suite now runs on Postgres and takes noticeably longer. Every new test class that +copies the container lines adds another container and another Spring context. Make the whole suite +share one of each kind.* + +**Steps before you change anything:** +1. `./inspect`. How many Postgres servers did your suite talk to? How many Spring contexts did it + start, and how long did each take? +2. `BookRepositoryTest` and `ShelfTest` are both `@DataJpaTest`. Why do they get different contexts? + +**Acceptance Criteria** (`./check 5`) +- [ ] Every Spring test runs on PostgreSQL: no H2 left, including `ShelfTest` and `CatalogueApiTest` +- [ ] One Postgres container for the whole run +- [ ] At most 2 Spring contexts: one for the `@DataJpaTest` classes, one for `@SpringBootTest` +- [ ] Inspect again: what changed in the numbers? + +**Hints:** +- An abstract base class with the container as a static field, started in a static block +- Spring caches a context by its whole configuration: properties, `@Import`, `@MockitoBean`, + `@ActiveProfiles`, `@DirtiesContext`, the container fields. Anything different is a new context +- `@DirtiesContext` throws away the context. Does it throw away the rows in the container? +- Expect some tests to go red when they share a database. That is Task 6 + +--- + +## Task 6: Tests That Own Their Data (20 min) + +**Story:** *Since the suite shares one database, `CatalogueApiTest` and `ShelfTest` fail, depending on +what ran before them. `CatalogueApiTest` is `@Transactional`, "so it rolls back". Find out what it +really rolls back.* + +**Acceptance Criteria** (`./check 6`) +- [ ] Every test that passes in the full run also passes on its own +- [ ] Every test gives the same result with classes and methods from Z to A (passes in `start/`, + where every class had a database of its own; sharing one in Task 5 breaks it) +- [ ] No test depends on the value of a generated id: the suite stays green with every id sequence + moved on by 1000 before each test +- [ ] `./check` baseline is green again + +**Hints:** +- Try the obvious fix first: in `listsTheShelf`, save the books with `BookRepository` instead of + relying on `addsABook`. Run it. Where did your books go? +- The HTTP request is handled on a server thread, in its own transaction +- Rolled back data is gone. Is a rolled back id given back? +- Clean before each test, not after: then any test can run first + +--- + +## Task 7: Order You Can Rely On (10 min) + +**Story:** *A shelf must list its books in the order they were added. `ShelfTest` says it does. It +says so on Postgres too. Make it prove it.* + +**Acceptance Criteria** (`./check 7`) +- [ ] Production: a shelf keeps its order after one of its books is rated +- [ ] Your suite catches the missing `ORDER BY`: with the `start/` query put back, a test fails + +**Hints:** +- Make the test red first. What does Postgres do to a row on UPDATE? +- `findByShelf` is a derived query. What does it put after `where`? + +--- + +## Task 8: Compare, and the Test Pyramid (10 min) + +**Story:** *"How would you test this service?" is the interview question. Collect the evidence, then +answer it.* + +**Steps:** +1. `./demo`. Compare with Task 1, line by line. +2. `./inspect`. Compare containers, contexts and start-up times with Task 5 step 1. +3. Which of your tests need Docker? Which do not? How long does each kind take? +4. Look at the rows left behind after the last test. Why are there any? +5. Your CI has no Docker. What are your options? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can say which tests should use a fake, which a real database, and which the whole app +- [ ] You can explain how the suite starts one container and keeps Spring's context cache warm +- [ ] You can say when an in-memory database is acceptable + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- Why not test the repository on H2? (H2 is a different database. Its "PostgreSQL mode" copies some + syntax, not the behaviour: here it sorts NULLs differently, returns rows in a different order, + cannot parse the real migration or `ON CONFLICT (...)`, and its schema came from Hibernate instead + of the migrations. A green test on H2 proves the code works on H2.) +- What is Testcontainers? (A library that starts real services, here Postgres, in throwaway Docker + containers from a test, and removes them afterwards. The test talks to the same database version + as production, built by the same migrations.) +- How does Spring Boot find the container? (`@ServiceConnection` on the container field: Boot reads + the URL, user and password from it. The older way is `@DynamicPropertySource`, a static method + that registers `spring.datasource.url` and friends from the container.) +- What does `@DataJpaTest` do to your database? (It is a slice: only JPA, repositories, Flyway and a + DataSource, and every test in a transaction that is rolled back. In Spring Boot 4 it replaces a + DataSource whose URL comes from ordinary properties with an embedded database if one is on the + classpath. It keeps a `@ServiceConnection` container or a `@DynamicPropertySource` URL. Use + `@AutoConfigureTestDatabase(replace = NONE)` to keep any URL.) +- Your suite takes 3 minutes because of containers. What do you do? (One container per JVM: a static + field started once, shared by every test class, not a JUnit `@Container` per class. Keep the test + configuration identical across classes so Spring's context cache reuses contexts: no stray + properties, no `@MockitoBean` in one class only, no `@DirtiesContext`. Locally, + `testcontainers.reuse.enable=true` can keep a container between runs; never rely on it in CI.) +- Is a mock of the repository enough? (For the service's logic, yes, and a hand-written fake is often + clearer. For the repository itself, no: a mock or fake does what you believe the SQL does. Queries, + constraints, migrations and transactions need the real database.) +- Your test is `@Transactional`, so it rolls back. Is the database clean? (Only of what ran in that + transaction. An HTTP call to the running server, an `@Async` method or a `REQUIRES_NEW` runs in + another transaction and commits. And the server cannot see what the test wrote in its own + uncommitted transaction. Sequences are not rolled back either.) +- A test passes alone and fails in the suite, or the other way round. Why? (It shares state with + another test: rows one left behind, rows one created that the other needs, or an id it assumes. + Each test should create its own data and start from a known state, for example by truncating the + tables before it runs.) +- Why not assert `id == 1`? (Ids come from a sequence. Rollbacks do not give them back, other tests + use them, a reused database continues where it was. Assert on the id the code returned.) +- Why did the order change after an UPDATE? (Without `ORDER BY` the database returns rows in whatever + order is cheapest. In Postgres an UPDATE writes a new version of the row, usually after the + others, so a plain scan returns it last. SQL promises no order without `ORDER BY`.) +- When is an in-memory database acceptable? (When the code under test does not depend on the + database: plain CRUD in a prototype, or a library that must run on several databases and is tested + on each. Not when production runs on a specific database with its own SQL, types and constraints.) +- What does the test pyramid look like for a Spring service? (Many fast unit tests for logic, with + fakes. A layer of integration tests on the real database for repositories, queries, migrations and + transactions. A few end-to-end tests through HTTP. Docker is a requirement for the middle layer, on + laptops and in CI.) + +## Tips for Interviewers + +- The most common answer is "I use H2 for tests". Ask what Postgres-specific SQL, types or constraints + the service uses, and how H2 would know about them. +- Ask the candidate to predict `./demo` in Task 1 before running it. A strong candidate expects the + NULL ordering problem before seeing it. +- Watch Task 4. A candidate who deletes the fake test has missed the point: the fake is right for the + logic, wrong for the SQL. +- Task 5 separates levels. A junior adds `@Container` to every class. A mid-level candidate shares one + container. A strong one explains why two `@DataJpaTest` classes got two contexts, and what + `@DirtiesContext` does not clean. +- In Task 6, ask why the `@Transactional` HTTP test could not see its own rows. A candidate who + answers "the server runs in another thread with its own transaction" understands what a test + transaction is. +- For senior candidates: how do you run this in CI without Docker-in-Docker, and how do you keep a + suite of 2,000 integration tests under five minutes? diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/README.md b/java/concepts/junior-mid/17-testing-with-a-real-database/README.md new file mode 100644 index 0000000..3d4e71a --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/README.md @@ -0,0 +1,199 @@ +# Testing With a Real Database — Testcontainers Instead of H2 and Mocks + +> **In `start/`, `./check` FAILS on purpose: 9 of 24 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5, 6 and 7 turn the other 15 green. + +A bookshop's test suite is green. Every test passes, in a few seconds, with no Docker. Then the code +goes to production on Postgres and four things break on the first day: the "top rated" page shows a +book nobody has reviewed at number 1, adding an audiobook fails, subscribing to the newsletter +fails for everyone, and a shelf lists its books in a different order after somebody rates one. + +The tests ran on H2, a database that pretends to be Postgres, and on a hand-written fake. This +project lets you watch your own tests say GREEN while production says BROKEN, then move the tests +onto a real Postgres with Testcontainers, keep them fast, and keep them from tripping over each +other. + +It answers the interview questions students most often get wrong: + +- "How do you test your repository layer? Why not H2?" +- "What is Testcontainers? How do you stop it from making the test suite slow?" +- "`@DataJpaTest` or `@SpringBootTest`? What does `@DataJpaTest` do with your database?" +- "Is a mock of the repository enough? When is a fake fine?" +- "Your test is `@Transactional`, so it rolls back. Is the database clean after it?" +- "A test passes on its own and fails in the full suite. Why?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4**, Spring Data JPA (**Hibernate 7**), Flyway +- **PostgreSQL 17** in Docker +- JUnit 6 (Jupiter), AssertJ, **Testcontainers 2**, H2 (in `start/`, as the tests use it; in both folders, + for the checks that compare it with Postgres) + +## 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 # the "production" Postgres, on port 5456 +./demo # your tests say GREEN, production says BROKEN +./check # 9 of 24 pass: that is your starting point +``` + +The first run downloads Maven, the dependencies and the Postgres image, so it takes a few minutes. + +When you are finished: `docker compose down -v`. + +## The three tools + +### `./demo` — your tests next to production + +Runs your test suite, one line per test, and shows which database each test class used. Then it +starts the real application on the Postgres from `compose.yaml` (emptied first, then built by the +Flyway migrations, as in production) and tries the same four features. The last line is the +verdict: + +``` +RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 4 of 4 features are broken on Postgres. +``` + +### `./inspect` — what your tests really did + +Runs your test suite once with a recorder attached and prints what happened underneath: the +database each test class talked to (H2 or Postgres, and its URL), where each schema came from +(Flyway or Hibernate), how many Postgres containers and Spring contexts were started and how long +each context took to start, and the rows left in the tables after the last test. + +### `./check` — are the acceptance criteria met? + +`./check 2` runs the checks for Task 2 and prints one line per criterion. `./check` runs everything. +`./mvnw verify` runs the same checks the usual Maven way. + +**Never edit, delete or disable anything under `check/`.** + +## Two kinds of test in this project + +This project is about **your tests**, so it has two layers. Keep them apart: + +| | Your test suite | The acceptance checks | +|---|---|---| +| Where | `src/test/java/com/amigoscode/realdb/` (everything except `check/`) | `src/test/java/com/amigoscode/realdb/check/` | +| Who writes it | You. In `start/` it runs on H2 and a fake, and it is green | Given. You never change it | +| Run by | `./mvnw test`, `./demo`, `./inspect` | `./check`, `./mvnw verify` | + +The checks ask two kinds of question. + +**"Production: ..."** checks run the code in `src/main` with its Flyway migrations against the +checks' own Postgres container. They do not look at your tests. They tell you the code works. + +**"Your suite: ..."** checks run your test classes through the JUnit launcher, the same way an IDE +does, and judge the suite itself: + +- **Which database did it use?** A Spring test listener, registered in + `src/test/resources/META-INF/spring.factories`, notes for every test class the Spring context it + got, the database behind it (product, URL, Postgres's server id), and whether its schema has a + `flyway_schema_history` table. Counting distinct server ids counts containers; counting distinct + contexts counts context starts. Nothing is timed. +- **Would it catch the bug?** The check puts one bug from `start/` back into the fixed code and runs + your suite again. Three bugs are repository queries: the checks wrap `BookRepository` and + `SubscriberRepository` in your test contexts, and while a bug is switched on, `findTopRated`, + `findByShelf` or `subscribe` runs the `start/` SQL. The fourth adds a constraint that rejects + `AUDIOBOOK` to any database your tests built with Flyway, as if V2 had never run. Your suite + "catches" the bug if a test that is green without it turns red with it. A test only counts if it + is also green when the suite runs a second time without the bug, so a test that breaks for some + other reason cannot catch anything by accident. This is called mutation testing. +- **Is every test independent?** Your suite runs A to Z, then Z to A, then every test on its own, + then with every id sequence moved on by 1000 just before each test. A test may not change its + result between these runs. + +The wrappers do nothing during `./mvnw test`: only a check switches a bug on. They are the same for +every test class, so they never stop two of your classes from sharing a Spring context. Because the +checks call them by name, **do not rename `findTopRated`, `findByShelf` or `subscribe`**, and keep +the test class names `BookRepositoryTest` and `SubscriptionServiceTest`. + +## The code + +``` +start/src/main/java/com/amigoscode/realdb/ +├── catalogue/ +│ ├── Book.java the entity: title, format, rating (null = no reviews), shelf +│ ├── Format.java PAPERBACK, HARDCOVER, EBOOK, AUDIOBOOK (new) +│ ├── BookRepository.java findTopRated, findByShelf. TWO BUGS ARE HERE +│ ├── CatalogueService.java add, rate, top rated, shelf +│ └── CatalogueController.java /api/books, /api/shelves/{shelf} +└── subscription/ + ├── SubscriberRepository.java subscribe: one INSERT ... ON CONFLICT. A BUG IS HERE + └── SubscriptionService.java checks the address, then subscribes +start/src/main/resources/db/migration/ +└── V1__create_catalogue.sql the real schema. A MIGRATION IS MISSING + +start/src/test/java/com/amigoscode/realdb/ YOUR TEST SUITE +├── catalogue/ +│ ├── BookRepositoryTest.java @DataJpaTest on H2 +│ ├── ShelfTest.java @DataJpaTest on H2, with one extra property +│ └── CatalogueApiTest.java @SpringBootTest over HTTP, H2 in PostgreSQL mode, @Transactional +├── subscription/ +│ ├── SubscriptionServiceTest.java unit tests with... +│ └── FakeSubscriberRepository.java ...an in-memory fake +└── check/ the acceptance checks and ./demo, ./inspect. Never edit +``` + +## 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 it break: green on H2, broken on Postgres | `./check 1` (passes: it documents the differences) | +| 2 | Run the repository tests on Postgres, fix what they find | `./check 2` | +| 3 | Inspect: which database did your test really use? | `./check 3` (passes: it documents what `@DataJpaTest` does) | +| 4 | Replace the fake where it hides the SQL | `./check 4` | +| 5 | One container, one context per kind of test | `./check 5` | +| 6 | Tests that own their data: the `@Transactional` trap | `./check 6` | +| 7 | Order you can rely on | `./check 7` | +| 8 | Compare, and the test pyramid | you answer questions | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 24 of 24. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +

+Spoiler: the bugs and the fixes + +**Four bugs that H2 and the fake hide.** Each one was confirmed on H2 2.4 and Postgres 17. + +| Bug | On H2 / the fake | On Postgres | Fix | +|---|---|---|---| +| `order by rating desc` | NULLs sort last: unrated books at the bottom | NULLs sort first in DESC: an unrated book is number 1 | `order by b.rating desc nulls last, b.id` | +| `AUDIOBOOK` added to the enum, not to the schema | Hibernate builds the H2 schema from the enum, so it accepts it | V1's check constraint rejects it | `V2__allow_audiobooks.sql` | +| `on conflict (email) do nothing` | H2 cannot even parse it, so the service was tested with a fake that "worked" | No unique index matches `(email)`: the index is on `lower(email)`. Every subscribe fails | `on conflict (lower(email)) do nothing` | +| `findByShelf` with no `ORDER BY` | Rows come back in primary key order | An UPDATE writes the row's new version after the others: the updated book comes back last | `order by b.addedAt, b.id` | + +**The tests.** + +- One Postgres container for the whole run: a static field in an abstract `PostgresTest` that every + database test extends, started once, with `@ServiceConnection`. The schema comes from the Flyway + migrations. +- `@DataJpaTest` keeps a `@ServiceConnection` container. A URL from `application.properties` it + replaces with an embedded H2 unless you add `@AutoConfigureTestDatabase(replace = NONE)`. +- Same container, same configuration in every class: 2 Spring contexts (one `@DataJpaTest`, one + `@SpringBootTest`) instead of one per class. +- The fake stays for the service's own logic; the SQL gets a `@DataJpaTest` on Postgres. +- No `@Transactional` on the HTTP test: the server commits on its own thread. Every test starts by + truncating the tables, and asserts on ids it got back, never on `1`. +- An order you rely on is an `ORDER BY` you wrote, and a test that updates a row before reading. + +
diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md b/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md new file mode 100644 index 0000000..abc5a08 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/TASKS_GUIDED.md @@ -0,0 +1,893 @@ +# Guided Tasks — Testing With a Real Database + +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`. + +Ports, ids, server ids and timings will differ on your machine. The test names, the counts and the +`RESULT` line should match. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +--- + +## Task 1: See It Break + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +### What you should see + +``` +1. YOUR TEST SUITE (src/test/java, everything outside check/) + + [GREEN] BookRepositoryTest.savesAnAudiobook + [GREEN] BookRepositoryTest.topRatedComesBestFirstAndUnratedBooksLast + [GREEN] CatalogueApiTest.addsABook + [GREEN] CatalogueApiTest.listsTheShelf + [GREEN] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded + [GREEN] SubscriptionServiceTest.aNewAddressIsSubscribed + [GREEN] SubscriptionServiceTest.rejectsSomethingThatIsNotAnEmailAddress + [GREEN] SubscriptionServiceTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce + + 8 tests: 8 green, 0 red, in 6776 ms. The database each test class used: + + test class database url + ----------------------- ---------- ------------------------------------------------ + BookRepositoryTest H2 2.4.240 jdbc:h2:mem:f6088562-538e-4f63-a024-e4aec2f7e023 + CatalogueApiTest H2 2.4.240 jdbc:h2:mem:catalogue + ShelfTest H2 2.4.240 jdbc:h2:mem:6646fafe-5a6a-417e-a24d-9d8d119cae5a + SubscriptionServiceTest none no Spring context: a plain unit test + +2. PRODUCTION: the same features, the code in src/main, on PostgreSQL 17.12 + (compose.yaml, jdbc:postgresql://localhost:5456/shop), schema from Flyway: V1 create catalogue + + [BROKEN] Top rated + added: Dune 4.8, Emma 3.9, No Reviews Yet (no rating), Hamlet 4.2 + top 3: No Reviews Yet (no rating), Dune 4.8, Hamlet 4.2 + A book nobody has reviewed is ahead of the best rated ones. + [BROKEN] Add an audiobook + ERROR: new row for relation "book" violates check constraint "book_format_check" + [BROKEN] Subscribe ann@example.com, then Ann@Example.COM + ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification + [BROKEN] Shelf "classics" after a review of Beloved + added: Beloved, Middlemarch, Rebecca. Then Beloved got a rating. + listed: Middlemarch, Rebecca, Beloved + Not the order they were added in. + +RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 4 of 4 features are broken on Postgres. +``` + +Every test is green. Every feature is broken. + +### Why each test stayed green + +Look at the database column first: three test classes ran on H2, one on no database at all. + +| Feature | The test | Why it is green | +|---|---|---| +| Top rated | `BookRepositoryTest.topRated...` | Same query, same data. H2 sorts the NULL rating **last** in `desc` order, Postgres sorts it **first** | +| Audiobook | `BookRepositoryTest.savesAnAudiobook` | `spring.flyway.enabled=false`: Hibernate built the H2 tables from the entities, and the entity knows `AUDIOBOOK`. The real schema is `V1__create_catalogue.sql`, whose `CHECK` constraint does not | +| Subscribe | `SubscriptionServiceTest` | A fake repository. The SQL never runs anywhere | +| Shelf order | `ShelfTest` | It never updates a row. And on H2 rows come back in primary key order anyway | + +`CatalogueApiTest` uses "H2 in PostgreSQL mode" (`MODE=PostgreSQL` in its URL). That mode copies +some Postgres syntax. It is still H2: same sort order, same storage, same parser. + +### The differences, in plain SQL + +```bash +./check 1 +``` + +``` +Task 1: See it break: H2 and Postgres disagree + [PASS] H2 vs Postgres: without ORDER BY, H2 returns rows by primary key, Postgres returns the row you just updated last + [PASS] H2 vs Postgres: ORDER BY rating DESC puts the NULL rating last on H2 (PostgreSQL mode), first on Postgres + [PASS] H2 vs Postgres: H2 cannot parse the real schema's index on lower(email) or ON CONFLICT (email); Postgres can, and rejects ON CONFLICT (email) because no index matches it + 3 of 3 pass +``` + +These pass on purpose. Each one runs the same statements on H2 and on a real Postgres and pins down +what each database answered (see `check/H2VersusPostgresIT.java`). + +> H2's own documentation suggests adding `DEFAULT_NULL_ORDERING=HIGH` to the URL for PostgreSQL +> mode. That would fix one of the four. To configure a difference away, you first have to know about +> it, and that is exactly what you do not know before production tells you. + +--- + +## Task 2: Run the Repository Tests on Postgres + +**The idea:** test the repository against the database production uses, built by the migrations +production uses. Testcontainers starts a throwaway Postgres in Docker for the test run. + +### Step 1: give BookRepositoryTest a real Postgres + +In `catalogue/BookRepositoryTest`, delete the class comment (it is no longer true) and replace: + +```java +@DataJpaTest(properties = { + "spring.flyway.enabled=false", + "spring.jpa.hibernate.ddl-auto=create-drop"}) +class BookRepositoryTest { +``` + +with: + +```java +@DataJpaTest +class BookRepositoryTest { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } +``` + +Imports: `org.springframework.boot.testcontainers.service.connection.ServiceConnection` and +`org.testcontainers.postgresql.PostgreSQLContainer`. The dependencies are already in `pom.xml`. + +Three things happened: + +- **The container.** A static field, started once in a static block, before Spring starts. Same + image as `compose.yaml`. +- **`@ServiceConnection`.** Spring Boot reads the JDBC URL, user and password from the container. You + write no URL. (The older way, still fine, is a `@DynamicPropertySource` method that registers + `spring.datasource.url`, `username` and `password` from `POSTGRES::getJdbcUrl` and friends. The + checks' own base class `check/support/ProductionTest.java` does it that way.) +- **No more properties.** Flyway is back on, so the schema comes from `db/migration`, and Hibernate + no longer invents one. + +### Step 2: watch it go red + +Do not fix anything yet. A test you have never seen fail proves nothing. + +```bash +./demo +``` + +``` + [RED] BookRepositoryTest.savesAnAudiobook + ERROR: new row for relation "book" violates check constraint "book_format_check" Detail: Failing row contains (1, Dune, AUDIOBOOK, null, fiction, 2026... + [RED] BookRepositoryTest.topRatedComesBestFirstAndUnratedBooksLast + Expecting actual: ["No Reviews Yet", "Dune", "Hamlet"] to contain exactly (and in same order): + ... + BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:54728/test?loggerLevel=OFF + ... +RESULT: BROKEN, AND YOUR TESTS SEE IT. 2 of 8 tests fail, and 4 of 4 features are broken on Postgres. +``` + +The same two tests, unchanged, now fail with the same errors as production. That is the whole point: +your test now runs where your bug lives. + +### Step 3: fix the code + +In `BookRepository`, put the unrated books last, and add a tie-breaker so equal ratings always come +back in the same order: + +```java +@Query("select b from Book b order by b.rating desc nulls last, b.id") +List findTopRated(Limit limit); +``` + +(`where b.rating is not null` would also be correct: an unrated book is not "top rated". Either +passes the checks.) + +Then add the migration the enum change needed. Create +`src/main/resources/db/migration/V2__allow_audiobooks.sql`: + +```sql +alter table book drop constraint book_format_check; +alter table book add constraint book_format_check + check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK', 'AUDIOBOOK')); +``` + +Never edit `V1`: it has already run in production, and Flyway would refuse to start because its +checksum changed. Schema changes are new migrations. + +### After + +```bash +./check 2 +``` + +``` +Task 2: Run the repository tests on Postgres, fix what they find + [PASS] Production: an AUDIOBOOK can be added (on Postgres, with the Flyway migrations) + [PASS] Production: top rated lists the best rated books first, and never an unrated book ahead of a rated one (on Postgres) + [PASS] Your suite: BookRepositoryTest runs on PostgreSQL, not H2 + [PASS] Your suite: BookRepositoryTest's schema comes from the Flyway migrations, not from Hibernate + [PASS] Your suite: catches the missing migration (a test fails when the database rejects AUDIOBOOK) + [PASS] Your suite: catches the top rated bug (a test fails when findTopRated has no NULLS LAST) + 6 of 6 pass +``` + +The last two are the interesting ones. The check put the `start/` query back (and, separately, +made the database reject `AUDIOBOOK` again) and ran your suite: a test turned red each time. In +`start/` the same checks failed, because the H2 tests stayed green with the bugs in. + +`./demo` now says `[OK]` for "Top rated" and "Add an audiobook", and +`RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. 8 of 8 tests pass, and 2 of 4 features are broken on Postgres.` +Two to go. + +--- + +## Task 3: Inspect Which Database Your Test Really Used + +### Step 1: what ran where + +```bash +./inspect +``` + +``` +DATABASE EACH TEST CLASS USED + test class database url + ----------------------- ---------------- ------------------------------------------------------ + BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:55721/test?loggerLevel=OFF + CatalogueApiTest H2 2.4.240 jdbc:h2:mem:catalogue + ShelfTest H2 2.4.240 jdbc:h2:mem:bc0099e2-2a6e-46c8-97c3-07ab8d6f12ef + SubscriptionServiceTest none no Spring context: a plain unit test + +WHERE EACH SCHEMA CAME FROM + context 1: Flyway migrations V1 create catalogue, V2 allow audiobooks + context 2: unknown: the context was closed (@DirtiesContext), its database with it + context 3: made up by Hibernate from the entities (no flyway_schema_history table) +``` + +`BookRepositoryTest` now has the real schema, both migrations. `ShelfTest` still runs on a schema +Hibernate made up. + +### Step 2: who chose H2? + +`ShelfTest`'s URL is `jdbc:h2:mem:`. Nobody wrote that. `application.properties` says +`jdbc:postgresql://localhost:5456/shop`. **`@DataJpaTest` replaced it.** + +`@DataJpaTest` includes `@AutoConfigureTestDatabase`. In Spring Boot 4 its default is +`replace = NON_TEST`: if an embedded database (H2, HSQLDB, Derby) is on the test classpath, it swaps +your DataSource for a fresh in-memory one, **unless** the DataSource is clearly a test database: + +```bash +./check 3 +``` + +``` +Task 3: Inspect what @DataJpaTest does with your database + [PASS] @DataJpaTest: a datasource URL from application.properties is swapped for an embedded H2 + [PASS] @DataJpaTest: a @ServiceConnection container is kept, with no extra annotation: the test runs on Postgres + [PASS] @DataJpaTest: with @AutoConfigureTestDatabase(replace = NONE) the same URL is kept: the test runs on Postgres + 3 of 3 pass +``` + +| The URL comes from | `@DataJpaTest` does | +|---|---| +| `application.properties`, or `@DataJpaTest(properties = ...)` | Replaces it with an embedded H2 | +| A `@ServiceConnection` container | Keeps it | +| A `@DynamicPropertySource` method | Keeps it | +| Anything, with `@AutoConfigureTestDatabase(replace = NONE)` (or `spring.test.database.replace=none`) | Keeps it | + +Spring Boot 3.3 and older replaced it whatever its source, which is why most Testcontainers +examples online carry `@AutoConfigureTestDatabase(replace = NONE)`. + +### Step 3: break it on purpose + +In `BookRepositoryTest`, comment out `@ServiceConnection` (keep the container and the static block) +and run `./inspect`: + +``` + [FAIL] BookRepositoryTest.savesAnAudiobook + Unknown data type: "TIMESTAMPTZ"; SQL statement: create table book ( id bigint generated by default as identity primary key, + ... + BookRepositoryTest none its Spring context did not start (see the failure above) +``` + +The container started, but Spring no longer knew about it. The URL came from +`application.properties`, so `@DataJpaTest` swapped in an embedded H2, and Flyway ran the real +migration on it. H2 does not even know Postgres's `timestamptz` type. **Put `@ServiceConnection` +back.** + +### Step 4: what a slice loads + +| | `@DataJpaTest` | `@SpringBootTest` | +|---|---|---| +| Loads | JPA, repositories, the DataSource, Flyway | The whole application | +| Web layer | No | Yes, a real server with `RANDOM_PORT` | +| Transactions | Every test in one, rolled back at the end | Only what your code opens | +| Use it for | Queries, mappings, constraints, migrations | A request through every layer | + +### What to take away + +- Always check which database a test really used. `./inspect` here; in a real project, log or assert + `connection.getMetaData().getURL()` once. +- `@DataJpaTest` replaces a DataSource it does not recognise as a test database. A + `@ServiceConnection` container is recognised. + +--- + +## Task 4: Replace the Fake Where It Hides the SQL + +### Step 1: test the SQL itself + +Create `src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java`: + +```java +package com.amigoscode.realdb.subscription; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.postgresql.PostgreSQLContainer; + +@DataJpaTest +class SubscriberRepositoryTest { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @Autowired + SubscriberRepository subscribers; + + @Test + void subscribesANewAddress() { + assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1); + assertThat(subscribers.count()).isEqualTo(1); + } + + @Test + void theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce() { + assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1); + assertThat(subscribers.subscribe("Ann@Example.COM")).isEqualTo(0); + + assertThat(subscribers.count()).isEqualTo(1); + } +} +``` + +The container lines are copied from `BookRepositoryTest`. Leave them for now: Task 5 deals with that. + +```bash +./demo +``` + +``` + [RED] SubscriberRepositoryTest.subscribesANewAddress + ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification + [RED] SubscriberRepositoryTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce + ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification + [GREEN] SubscriptionServiceTest.aNewAddressIsSubscribed + [GREEN] SubscriptionServiceTest.rejectsSomethingThatIsNotAnEmailAddress + [GREEN] SubscriptionServiceTest.theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce +``` + +Even the very first subscribe fails. The fake test right below says the same feature works. + +### Why + +`V1__create_catalogue.sql` makes addresses unique ignoring case: + +```sql +create unique index subscriber_email_key on subscriber (lower(email)); +``` + +`ON CONFLICT (email)` asks Postgres for a unique index on the column `email`. There is none: the +index is on the expression `lower(email)`. Postgres checks this before it inserts anything, so the +statement fails every time. The fake lower-cases the address in Java and never runs SQL, so it +"works". H2 cannot parse the statement at all, which is why the fake was written in the first place. + +### Step 2: fix the SQL + +In `SubscriberRepository.subscribe`, name the expression the index is built on: + +```java +@Query(value = """ + insert into subscriber (email) values (:email) + on conflict (lower(email)) do nothing + """, nativeQuery = true) +int subscribe(@Param("email") String email); +``` + +### Step 3: keep the fake, for what it is good at + +The fake is not wrong. It is the right tool for the service's own logic: the email check, and "0 +rows means ALREADY_SUBSCRIBED". Those tests run in milliseconds without Spring or Docker. Rename the +one that pretends to be about SQL, so it says what it really tests: in `SubscriptionServiceTest`, +rename `theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce` to +`whenTheRepositoryAddsNothingTheAddressWasAlreadySubscribed`. + +| Fake or mock is fine | Needs the real database | +|---|---| +| Decisions in the service: validation, mapping, what a result means | Every query you wrote, native or JPQL | +| Calls to other services | Constraints, indexes, `ON CONFLICT`, migrations | +| Error handling paths | Transactions, locks, isolation | + +### After + +```bash +./check 4 +``` + +``` +Task 4: Replace the fake where it hides the SQL + [PASS] Production: subscribing ann@example.com, then Ann@Example.COM, keeps one subscriber and answers ALREADY_SUBSCRIBED (on Postgres) + [PASS] Your suite: SubscriptionServiceTest still tests the service's logic with the fake, with no Spring and no database + [PASS] Your suite: catches the ON CONFLICT bug (a test fails when subscribe uses ON CONFLICT (email)) + 3 of 3 pass +``` + +--- + +## Task 5: One Container, One Context per Kind of Test + +### Step 1: count + +```bash +./inspect +``` + +``` +POSTGRES SERVERS (one per container): 2 + server id started at used by contexts + ------------------- ------------ ---------------- + 7714810932418117666 20:46:35.912 1 + 7714810951974785058 20:46:40.440 4 + +SPRING CONTEXTS STARTED: 4 + # kind start-up used by + - --------------- -------- ------------------------ + 1 @DataJpaTest 2,109 ms BookRepositoryTest + 2 @SpringBootTest 745 ms CatalogueApiTest + 3 @DataJpaTest 115 ms ShelfTest + 4 @DataJpaTest 252 ms SubscriberRepositoryTest +``` + +Two containers, because two classes each declare their own. Four contexts for two kinds of test. + +**Spring's test context cache.** Spring keeps every context it starts in a cache, keyed by the test +class's whole configuration: the slice, `properties`, `@Import`, `@ActiveProfiles`, +`@MockitoBean`/`@MockitoSpyBean` fields, `@DynamicPropertySource` methods, `@ServiceConnection` +fields. Two classes with exactly the same configuration share one context. Here every class is +different: + +- `BookRepositoryTest` and `SubscriberRepositoryTest` each declare **their own** container field. +- `ShelfTest` has `properties = {... "spring.jpa.properties.hibernate.format_sql=true"}`, left over + from debugging. One harmless property, one more context. +- `CatalogueApiTest` has `@DirtiesContext`, which closes its context after the class. The next class + that needs one starts it again. It does nothing to the rows in a database container. + +With 4 test classes the cost is seconds. With 200 test classes it is the difference between 1 and +15 minutes. + +### Step 2: one base class + +Create `src/test/java/com/amigoscode/realdb/support/PostgresTest.java`: + +```java +package com.amigoscode.realdb.support; + +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** One Postgres for the whole test run. Every test class that needs a database extends this class. */ +public abstract class PostgresTest { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } +} +``` + +A static field is created once per JVM, however many classes extend it. It is not stopped after +each class: Testcontainers removes it when the JVM ends. + +> **Why not `@Testcontainers` and `@Container`?** That JUnit extension starts the container before +> each test class and stops it after. With Spring's context cache it is worse than slow: the next run +> of the same configuration gets a cached context that still points at the stopped container's old +> port, and usually fails with `Connection refused` (the checks run your suite several times in one +> JVM). Use `@Container` only for a container that belongs to one class and has no cached context. + +### Step 3: every database test extends it + +- `BookRepositoryTest` and `SubscriberRepositoryTest`: delete the container field, the static block + and their two imports; add `extends PostgresTest` and import + `com.amigoscode.realdb.support.PostgresTest`. +- `ShelfTest`: replace its whole `@DataJpaTest(properties = {...})` with `@DataJpaTest`, and + `extends PostgresTest`. +- `CatalogueApiTest`: replace the `@SpringBootTest(...)` with + `@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)`, delete + `@DirtiesContext` and its import, and `extends PostgresTest`. Leave `@Transactional` and the + `@Order`s for Task 6. + +### Step 4: count again + +```bash +./inspect +``` + +``` + [FAIL] CatalogueApiTest.addsABook + expected: 1L but was: 6L + [PASS] CatalogueApiTest.listsTheShelf + [FAIL] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded + Expecting actual: ["Beloved", "Beloved", "Middlemarch", "Rebecca"] to contain exactly (and in same order): ["Beloved", "Middlemarch", "Rebecca"] +... +POSTGRES SERVERS (one per container): 1 + server id started at used by contexts + ------------------- ------------ ---------------- + 7714812563007639585 20:52:58.139 1, 2 + +SPRING CONTEXTS STARTED: 2 + # kind start-up used by + - --------------- -------- ------------------------------------------------------- + 1 @DataJpaTest 5,441 ms BookRepositoryTest, ShelfTest, SubscriberRepositoryTest + 2 @SpringBootTest 1,947 ms CatalogueApiTest +``` + +One server, two contexts: one per kind of test. That is the floor: a `@DataJpaTest` and a +`@SpringBootTest` are different configurations and can never share. (Your start-up times will +differ; that is why the checks count contexts and never measure time.) + +```bash +./check 5 +``` + +``` +Task 5: One container, one context per kind of test + [PASS] Your suite: at most 2 Spring contexts, one per kind of test (@DataJpaTest, @SpringBootTest) + [PASS] Your suite: every Spring test runs on PostgreSQL (no H2 left) + [PASS] Your suite: one Postgres container for the whole run, shared by every test class + 3 of 3 pass +``` + +Two tests went red. On H2, every class had a database of its own, so tests could not see each +other. Now they share one, and they do. That is Task 6. + +> **Testcontainers reuse.** With `.withReuse(true)` on the container and +> `testcontainers.reuse.enable=true` in `~/.testcontainers.properties`, Testcontainers leaves the +> container running after the JVM ends and the next run attaches to it: no start-up at all. It is a +> local convenience. The data survives between runs too, nothing removes the container for you, and +> CI should always start fresh. + +--- + +## Task 6: Tests That Own Their Data + +### Step 1: what failed, and why + +```bash +./check 6 +``` + +``` +Task 6: Tests that own their data + [FAIL] Your suite: every test gives the same result with classes and methods run from Z to A + The order changes the result. Some test leaves data behind that another one trips over: + CatalogueApiTest.listsTheShelf passes A to Z, fails Z to A: Expecting actual: ["Beloved", "Beloved"] to contain exactly (and in same order): ["Beloved"] + [FAIL] Your suite: every test that passes in the full run also passes when it runs on its own + ... + 0 of 3 pass +``` + +Three problems, all from sharing a database: + +- **`addsABook` expects id 1 and gets 6.** `BookRepositoryTest` ran first. Its inserts were rolled + back, but **sequences are never rolled back**: ids 1 to 5 are used up for good. +- **`listsTheShelf` needs `addsABook`** to have run first (`@Order(2)`) and left "Beloved" behind. +- **`ShelfTest` finds two "Beloved"s.** `@DataJpaTest` rolls back *its own* test. It cannot remove + the row `CatalogueApiTest` committed before it. + +### Step 2: the obvious fix, and the trap + +Make `listsTheShelf` create its own books. The class is `@Transactional`, so they will be rolled +back. In `CatalogueApiTest`: + +```java +@Autowired +BookRepository books; + +@Test +@Order(2) +void listsTheShelf() { + books.save(new Book("Beloved", Format.PAPERBACK, "fiction")); + books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction")); + + List shelf = http.get().uri("/api/shelves/fiction").retrieve() + .body(new ParameterizedTypeReference<>() { }); + + assertThat(shelf).extracting(BookView::title).containsExactly("Beloved", "Middlemarch"); +} +``` + +```bash +./demo +``` + +``` + [RED] CatalogueApiTest.listsTheShelf + Expecting actual: ["Beloved"] to contain exactly (and in same order): ["Beloved", "Middlemarch"] +``` + +The server returned **one** book: the "Beloved" that `addsABook` committed. The two books this test +saved are invisible. + +`@Transactional` on a test opens a transaction **on the test's thread**. `books.save` ran inside it, +uncommitted. The HTTP request is handled by the server on **another thread**, in **its own** +transaction, which cannot see uncommitted rows. And the other way round: everything the server +writes, it commits, and the test's rollback does not touch it. + +The same is true for anything that leaves the test's thread or transaction: an `@Async` method, a +`@Transactional(propagation = REQUIRES_NEW)` method, a message listener. A rolled back test only +cleans up what ran in its own transaction. + +### Step 3: the fix + +Every test starts from empty tables, whatever ran before it. In `PostgresTest`: + +```java +@Autowired +private DataSource dataSource; + +/** Every test starts from empty tables, whatever ran before it. */ +@BeforeEach +void startFromEmptyTables() { + new JdbcTemplate(dataSource).execute("truncate table book, subscriber"); +} +``` + +Imports: `javax.sql.DataSource`, `org.junit.jupiter.api.BeforeEach`, +`org.springframework.beans.factory.annotation.Autowired`, `org.springframework.jdbc.core.JdbcTemplate`. + +Clean **before** each test, not after: then no test depends on the previous one having tidied up, and +after a failure the rows are still there to look at. In a `@DataJpaTest` the truncate runs inside the +test's transaction, so it is rolled back with the rest, which is fine: that test only needs empty +tables while it runs. No `restart identity`: ids keep counting up, so no test can rely on them. + +Then replace the body of `CatalogueApiTest` from the annotations to the end of `listsTheShelf`: no +`@Transactional`, no order, every test adds its own books over HTTP, and the id comes from the +response: + +```java +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class CatalogueApiTest extends PostgresTest { + + @LocalServerPort + int port; + + RestClient http; + + @BeforeEach + void client() { + http = RestClient.create("http://localhost:" + port); + } + + @Test + void addsABook() { + ResponseEntity response = add("Beloved", "fiction"); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + long id = response.getBody().id(); + assertThat(response.getHeaders().getLocation()).hasToString("/api/books/" + id); + } + + @Test + void listsTheShelf() { + add("Beloved", "fiction"); + add("Middlemarch", "fiction"); + add("Ariel", "poetry"); + + List shelf = http.get().uri("/api/shelves/fiction").retrieve() + .body(new ParameterizedTypeReference<>() { }); + + assertThat(shelf).extracting(BookView::title).containsExactly("Beloved", "Middlemarch"); + } +``` + +Keep the `add` helper. Remove the imports that are no longer used (`MethodOrderer`, `Order`, +`TestMethodOrder`, `Transactional`, `Autowired`). + +### After + +```bash +./check 6 +``` + +``` +Task 6: Tests that own their data + [PASS] Your suite: every test gives the same result with classes and methods run from Z to A + [PASS] Your suite: every test that passes in the full run also passes when it runs on its own + [PASS] Your suite: no test depends on the value of a generated id (every sequence moved on by 1000 before each test) + 3 of 3 pass +``` + +The last check moved every id sequence on by 1000 just before each test body. In `start/` it failed +on `addsABook` with `expected: 1L but was: 1005000L`. On H2 the test only passed because +`@DirtiesContext` gave it a brand new database every time. + +--- + +## Task 7: Order You Can Rely On + +### Step 1: make the test able to fail + +`ShelfTest` passes on Postgres. Run `./check 7`: + +``` + [FAIL] Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY) + Your suite ran with the start/ version of findByShelf put back, and no test that passes now failed. + So it would not catch this bug. On Postgres, update one of the books (rate it) before you read the shelf, and assert on the order. +``` + +It passes by luck. Freshly inserted rows usually come back in insertion order, with or without +`ORDER BY`. Production rates books. In `ShelfTest`, keep the first book in a variable and rate it +before reading the shelf: + +```java +Book beloved = books.save(new Book("Beloved", Format.PAPERBACK, "fiction")); +books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction")); +books.save(new Book("Rebecca", Format.EBOOK, "fiction")); +books.save(new Book("Ariel", Format.PAPERBACK, "poetry")); + +beloved.rate(new BigDecimal("4.5")); +``` + +(Import `java.math.BigDecimal`.) `./demo`: + +``` + [RED] ShelfTest.shelfListsBooksInTheOrderTheyWereAdded + Expecting actual: ["Middlemarch", "Rebecca", "Beloved"] to contain exactly (and in same order): ["Beloved", "Middlemarch", "Rebecca"] +``` + +### Why + +Postgres never changes a row in place. An UPDATE writes a **new version** of the row in free space, +usually after the existing rows, and marks the old one dead. A query without `ORDER BY` reads the +table front to back, so the book you just rated comes back last. H2 keeps rows in primary key order, +so on H2 the same test cannot fail. SQL makes no promise about order without `ORDER BY`. Neither +database is wrong; the query is. + +### Step 2: fix the query + +In `BookRepository`: + +```java +/** The books on one shelf, in the order they were added. */ +@Query("select b from Book b where b.shelf = :shelf order by b.addedAt, b.id") +List findByShelf(@Param("shelf") String shelf); +``` + +Import `org.springframework.data.repository.query.Param`. `b.id` breaks ties when two books share a +timestamp. (A derived name like `findByShelfOrderByAddedAtAscIdAsc` would also work, but the checks +call `findByShelf`, so keep the name.) + +### After + +```bash +./check 7 +./check +``` + +``` +Task 7: Order you can rely on + [PASS] Production: a shelf lists its books in the order they were added, also after one of them is updated (on Postgres) + [PASS] Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY) + 2 of 2 pass +``` + +`./check` should now print 24 passes and no failures. + +Two rules about tests and order: + +- If the order is part of the contract, the query has an `ORDER BY`, and the test does something + (an update, a delete) that would break the order without it. +- If the order is not part of the contract, the test says so: `containsExactlyInAnyOrder`, not + `containsExactly`. Asserting an order nobody promised is a test that fails one day for no reason. + +--- + +## Task 8: Compare, and the Test Pyramid + +### Step 1: the same demo, again + +```bash +./demo +``` + +``` + BookRepositoryTest PostgreSQL 17.12 jdbc:postgresql://localhost:64204/test?loggerLevel=OFF + CatalogueApiTest PostgreSQL 17.12 jdbc:postgresql://localhost:64204/test?loggerLevel=OFF + ... + SubscriptionServiceTest none no Spring context: a plain unit test + ... +RESULT: OK. All 10 tests pass, and all 4 features work on Postgres. +``` + +One URL for every database test: one container. The fake test still needs nothing. Compare with +Task 1: the same features, the same kind of tests, and now they would have told you. + +### Step 2: what is left behind + +```bash +./inspect +``` + +``` +SPRING CONTEXTS STARTED: 2 + # kind start-up used by + - --------------- -------- ------------------------------------------------------- + 1 @DataJpaTest 2,362 ms BookRepositoryTest, ShelfTest, SubscriberRepositoryTest + 2 @SpringBootTest 854 ms CatalogueApiTest + +ROWS LEFT BEHIND AFTER THE LAST TEST + context database book subscriber + ------- ---------------- ---- ---------- + 1 PostgreSQL 17.12 3 0 + 2 PostgreSQL 17.12 3 0 +``` + +Both contexts point at the same database. The 3 books are `CatalogueApiTest.listsTheShelf`'s: it +committed them over HTTP. The `@DataJpaTest` classes that ran after it truncated the tables inside +their own transactions, and those were rolled back. Leftovers are fine, because every test cleans +**before** it starts. + +### Step 3: the test pyramid for a Spring service + +| Layer | What | How many | Tools here | Needs | +|---|---|---|---|---| +| Unit | Logic in services, mappers, validators | Most | JUnit, a fake (`SubscriptionServiceTest`) | Nothing. Milliseconds | +| Data access | Queries, mappings, constraints, migrations, transactions | One per query and rule | `@DataJpaTest` + Testcontainers | Docker. Seconds to start, then fast | +| End to end | A request through every layer | A few | `@SpringBootTest(RANDOM_PORT)` + Testcontainers | Docker | + +**Docker in CI.** GitHub Actions Linux runners, GitLab with a Docker service and most CI systems +have it. If yours does not, look for a remote Docker host or Testcontainers Cloud before you give up +on real databases; do not quietly switch to H2 in CI. + +**When an in-memory database is acceptable:** when the code does not depend on the database. A +prototype with plain CRUD, or a library that must run on several databases and is tested on each. +Not when production runs on Postgres and the code uses its SQL, types or constraints. + +### How to say it in an interview + +> "I test logic with plain unit tests, with a hand-written fake where the service needs a repository. +> Everything that talks to the database I test against the same database as production, with +> Testcontainers and the real Flyway migrations, because H2 behaves differently: it sorts NULLs +> differently, returns rows in a different order, and cannot run our migrations or our ON CONFLICT +> queries. A fake or a mock of the repository proves nothing about the SQL. To keep it fast I start +> one container per test run, a static field in a base class with @ServiceConnection, and keep the +> test configuration identical so Spring's context cache reuses contexts: no @DirtiesContext, no +> one-off properties or @MockitoBeans. Every test owns its data: it truncates the tables before it +> starts, never assumes an id, and I don't put @Transactional on tests that go through HTTP, because +> the server commits in its own transaction." + +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 -v +``` diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/solution/check b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check new file mode 100755 index 0000000..790e98e --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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.realdb.check.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/check.cmd new file mode 100644 index 0000000..eed036c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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.realdb.check.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml new file mode 100644 index 0000000..2d3ffc3 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/compose.yaml @@ -0,0 +1,16 @@ +name: testing-with-a-real-database +services: + postgres: + image: postgres:17-alpine + container_name: testing-with-a-real-database-postgres + environment: + POSTGRES_DB: shop + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + ports: + - "5456:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U shop -d shop"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo new file mode 100755 index 0000000..402789c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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 test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Demo -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/demo.cmd new file mode 100644 index 0000000..1b65591 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Demo" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect new file mode 100755 index 0000000..10bb2f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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 test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Inspect -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/inspect.cmd new file mode 100644 index 0000000..99f2d61 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Inspect" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/solution/mvnw.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/solution/pom.xml b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml new file mode 100644 index 0000000..0b7e35b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + testing-with-a-real-database + 0.0.1-SNAPSHOT + testing-with-a-real-database + Testing data access against a real Postgres with Testcontainers instead of H2 or mocks + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-flyway + + + org.flywaydb + flyway-database-postgresql + + + 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.springframework.boot + spring-boot-testcontainers + test + + + org.testcontainers + testcontainers-postgresql + test + + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + com.h2database + h2 + 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/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java new file mode 100644 index 0000000..5a8f484 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java @@ -0,0 +1,23 @@ +package com.amigoscode.realdb; + +import com.amigoscode.realdb.catalogue.BookNotFoundException; +import com.amigoscode.realdb.subscription.InvalidEmailException; +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class ApiExceptionHandler { + + @ExceptionHandler(BookNotFoundException.class) + ResponseEntity> notFound(BookNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("code", "BOOK_NOT_FOUND", "message", e.getMessage())); + } + + @ExceptionHandler(InvalidEmailException.class) + ResponseEntity> invalidEmail(InvalidEmailException e) { + return ResponseEntity.badRequest().body(Map.of("code", "INVALID_EMAIL", "message", e.getMessage())); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java new file mode 100644 index 0000000..f16f735 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.realdb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RealDatabaseApplication { + + public static void main(String[] args) { + SpringApplication.run(RealDatabaseApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java new file mode 100644 index 0000000..da07ac2 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Book.java @@ -0,0 +1,81 @@ +package com.amigoscode.realdb.catalogue; + +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.math.BigDecimal; +import java.time.Instant; + +@Entity +@Table(name = "book") +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String title; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private Format format; + + /** Average review score from 1.0 to 5.0. Null until the book has its first review. */ + @Column(precision = 2, scale = 1) + private BigDecimal rating; + + @Column(nullable = false) + private String shelf; + + @Column(name = "added_at", nullable = false) + private Instant addedAt; + + protected Book() { + } + + public Book(String title, Format format, String shelf) { + this.title = title; + this.format = format; + this.shelf = shelf; + this.addedAt = Instant.now(); + } + + public void rate(BigDecimal rating) { + this.rating = rating; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public Format getFormat() { + return format; + } + + public BigDecimal getRating() { + return rating; + } + + public String getShelf() { + return shelf; + } + + public Instant getAddedAt() { + return addedAt; + } + + @Override + public String toString() { + return title; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java new file mode 100644 index 0000000..028d096 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.catalogue; + +public class BookNotFoundException extends RuntimeException { + + public BookNotFoundException(long id) { + super("No book with id " + id); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java new file mode 100644 index 0000000..4f6b5c2 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java @@ -0,0 +1,19 @@ +package com.amigoscode.realdb.catalogue; + +import java.util.List; +import org.springframework.data.domain.Limit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +/** The acceptance checks call findTopRated and findByShelf by name: fix them, do not rename them. */ +public interface BookRepository extends JpaRepository { + + /** The best rated books first. A book without a rating has no reviews yet: it goes last. */ + @Query("select b from Book b order by b.rating desc nulls last, b.id") + List findTopRated(Limit limit); + + /** The books on one shelf, in the order they were added. */ + @Query("select b from Book b where b.shelf = :shelf order by b.addedAt, b.id") + List findByShelf(@Param("shelf") String shelf); +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java new file mode 100644 index 0000000..ea4458d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java @@ -0,0 +1,58 @@ +package com.amigoscode.realdb.catalogue; + +import java.math.BigDecimal; +import java.net.URI; +import java.util.List; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +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.RestController; + +@RestController +@RequestMapping("/api") +public class CatalogueController { + + public record NewBook(String title, Format format, String shelf) { + } + + public record NewRating(BigDecimal rating) { + } + + public record BookView(long id, String title, Format format, BigDecimal rating, String shelf) { + + static BookView of(Book book) { + return new BookView(book.getId(), book.getTitle(), book.getFormat(), book.getRating(), book.getShelf()); + } + } + + private final CatalogueService catalogue; + + public CatalogueController(CatalogueService catalogue) { + this.catalogue = catalogue; + } + + @PostMapping("/books") + public ResponseEntity addBook(@RequestBody NewBook request) { + Book book = catalogue.addBook(request.title(), request.format(), request.shelf()); + return ResponseEntity.created(URI.create("/api/books/" + book.getId())).body(BookView.of(book)); + } + + @PutMapping("/books/{id}/rating") + public BookView rate(@PathVariable long id, @RequestBody NewRating request) { + return BookView.of(catalogue.rate(id, request.rating())); + } + + @GetMapping("/books/top-rated") + public List topRated() { + return catalogue.topRated().stream().map(BookView::of).toList(); + } + + @GetMapping("/shelves/{shelf}") + public List shelf(@PathVariable String shelf) { + return catalogue.shelf(shelf).stream().map(BookView::of).toList(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java new file mode 100644 index 0000000..aa0e899 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java @@ -0,0 +1,41 @@ +package com.amigoscode.realdb.catalogue; + +import java.math.BigDecimal; +import java.util.List; +import org.springframework.data.domain.Limit; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class CatalogueService { + + static final int TOP_RATED_SIZE = 3; + + private final BookRepository books; + + public CatalogueService(BookRepository books) { + this.books = books; + } + + @Transactional + public Book addBook(String title, Format format, String shelf) { + return books.save(new Book(title, format, shelf)); + } + + @Transactional + public Book rate(long bookId, BigDecimal rating) { + Book book = books.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId)); + book.rate(rating); + return book; + } + + @Transactional(readOnly = true) + public List topRated() { + return books.findTopRated(Limit.of(TOP_RATED_SIZE)); + } + + @Transactional(readOnly = true) + public List shelf(String shelf) { + return books.findByShelf(shelf); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java new file mode 100644 index 0000000..df65f14 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/catalogue/Format.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.catalogue; + +public enum Format { + PAPERBACK, + HARDCOVER, + EBOOK, + AUDIOBOOK +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java new file mode 100644 index 0000000..5d8a0a7 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.subscription; + +public class InvalidEmailException extends RuntimeException { + + public InvalidEmailException(String email) { + super("Not an email address: " + email); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java new file mode 100644 index 0000000..5f73e69 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.subscription; + +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 = "subscriber") +public class Subscriber { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String email; + + @Column(name = "subscribed_at", nullable = false, insertable = false, updatable = false) + private Instant subscribedAt; + + protected Subscriber() { + } + + public Long getId() { + return id; + } + + public String getEmail() { + return email; + } + + public Instant getSubscribedAt() { + return subscribedAt; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java new file mode 100644 index 0000000..e610bac --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java @@ -0,0 +1,27 @@ +package com.amigoscode.realdb.subscription; + +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +/** The acceptance checks call subscribe by name: fix it, do not rename it. */ +public interface SubscriberRepository extends Repository { + + /** + * Adds the address unless it is already subscribed, in any capitalisation. One statement, so two + * requests for the same address at the same moment cannot both insert it. + * + * @return 1 if the address was added, 0 if it was already there + */ + @Modifying + @Transactional + @Query(value = """ + insert into subscriber (email) values (:email) + on conflict (lower(email)) do nothing + """, nativeQuery = true) + int subscribe(@Param("email") String email); + + long count(); +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java new file mode 100644 index 0000000..fe55578 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java @@ -0,0 +1,29 @@ +package com.amigoscode.realdb.subscription; + +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SubscriptionController { + + public record NewSubscriber(String email) { + } + + private final SubscriptionService subscriptions; + + public SubscriptionController(SubscriptionService subscriptions) { + this.subscriptions = subscriptions; + } + + /** 201 for a new subscriber, 200 if the address was already subscribed. */ + @PostMapping("/api/subscribers") + public ResponseEntity> subscribe(@RequestBody NewSubscriber request) { + SubscriptionService.Outcome outcome = subscriptions.subscribe(request.email()); + HttpStatus status = outcome == SubscriptionService.Outcome.SUBSCRIBED ? HttpStatus.CREATED : HttpStatus.OK; + return ResponseEntity.status(status).body(Map.of("outcome", outcome.name())); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java new file mode 100644 index 0000000..44c176d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java @@ -0,0 +1,27 @@ +package com.amigoscode.realdb.subscription; + +import java.util.regex.Pattern; +import org.springframework.stereotype.Service; + +@Service +public class SubscriptionService { + + public enum Outcome { SUBSCRIBED, ALREADY_SUBSCRIBED } + + private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+\\.[^@\\s]+"); + + private final SubscriberRepository subscribers; + + public SubscriptionService(SubscriberRepository subscribers) { + this.subscribers = subscribers; + } + + /** Subscribes an address to the newsletter. Subscribing twice is fine: the second time changes nothing. */ + public Outcome subscribe(String email) { + String address = email == null ? "" : email.strip(); + if (!EMAIL.matcher(address).matches()) { + throw new InvalidEmailException(email); + } + return subscribers.subscribe(address) == 1 ? Outcome.SUBSCRIBED : Outcome.ALREADY_SUBSCRIBED; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties new file mode 100644 index 0000000..7ba0fda --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/application.properties @@ -0,0 +1,13 @@ +spring.application.name=testing-with-a-real-database + +# Postgres from compose.yaml. Port 5456 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5456/shop} +spring.datasource.username=${DB_USER:shop} +spring.datasource.password=${DB_PASSWORD:shop} + +# The schema comes from Flyway (src/main/resources/db/migration), never from Hibernate. +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# Uncomment to see every SQL statement. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql new file mode 100644 index 0000000..d2d099d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V1__create_catalogue.sql @@ -0,0 +1,20 @@ +create table book ( + id bigint generated by default as identity primary key, + title text not null, + format varchar(20) not null, + rating numeric(2, 1), -- null until the book has its first review + shelf text not null, + added_at timestamptz not null default now(), + constraint book_format_check check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK')), + constraint book_rating_check check (rating between 1.0 and 5.0) +); + +create table subscriber ( + id bigint generated by default as identity primary key, + email text not null, + subscribed_at timestamptz not null default now() +); + +-- One subscription per address, whatever the capitalisation: +-- Ann@Example.com and ann@example.com are the same person. +create unique index subscriber_email_key on subscriber (lower(email)); diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql new file mode 100644 index 0000000..1e6c95a --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/main/resources/db/migration/V2__allow_audiobooks.sql @@ -0,0 +1,4 @@ +-- Format.AUDIOBOOK was added to the Java enum. The database has to accept it too. +alter table book drop constraint book_format_check; +alter table book add constraint book_format_check + check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK', 'AUDIOBOOK')); diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java new file mode 100644 index 0000000..473f9ba --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java @@ -0,0 +1,44 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.support.PostgresTest; +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.data.domain.Limit; + +/** The repository against real Postgres, with the schema from the Flyway migrations. */ +@DataJpaTest +class BookRepositoryTest extends PostgresTest { + + @Autowired + BookRepository books; + + @Test + void topRatedComesBestFirstAndUnratedBooksLast() { + rated("Dune", "4.8"); + rated("Emma", "3.9"); + books.save(new Book("No Reviews Yet", Format.PAPERBACK, "fiction")); + rated("Hamlet", "4.2"); + + assertThat(books.findTopRated(Limit.of(3))) + .extracting(Book::getTitle) + .containsExactly("Dune", "Hamlet", "Emma"); + } + + @Test + void savesAnAudiobook() { + Book saved = books.saveAndFlush(new Book("Dune", Format.AUDIOBOOK, "fiction")); + + assertThat(books.findById(saved.getId())).get() + .extracting(Book::getFormat) + .isEqualTo(Format.AUDIOBOOK); + } + + private void rated(String title, String rating) { + Book book = books.save(new Book(title, Format.PAPERBACK, "fiction")); + book.rate(new BigDecimal(rating)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java new file mode 100644 index 0000000..52384a8 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java @@ -0,0 +1,66 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.catalogue.CatalogueController.BookView; +import com.amigoscode.realdb.catalogue.CatalogueController.NewBook; +import com.amigoscode.realdb.support.PostgresTest; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClient; + +/** + * The whole application over HTTP, against the same Postgres as the other tests. + * + *

Not @Transactional: the server handles each request on its own thread, in its own transaction, + * and commits it. A transaction around the test would roll back nothing the server did, and the + * server could not see anything the test wrote in it. PostgresTest empties the tables before each test. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class CatalogueApiTest extends PostgresTest { + + @LocalServerPort + int port; + + RestClient http; + + @BeforeEach + void client() { + http = RestClient.create("http://localhost:" + port); + } + + @Test + void addsABook() { + ResponseEntity response = add("Beloved", "fiction"); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + long id = response.getBody().id(); + assertThat(response.getHeaders().getLocation()).hasToString("/api/books/" + id); + assertThat(response.getBody().title()).isEqualTo("Beloved"); + } + + @Test + void listsTheShelf() { + add("Beloved", "fiction"); + add("Middlemarch", "fiction"); + add("Ariel", "poetry"); + + List shelf = http.get().uri("/api/shelves/fiction").retrieve() + .body(new ParameterizedTypeReference<>() { }); + + assertThat(shelf).extracting(BookView::title).containsExactly("Beloved", "Middlemarch"); + } + + private ResponseEntity add(String title, String shelf) { + return http.post().uri("/api/books") + .body(new NewBook(title, Format.PAPERBACK, shelf)) + .retrieve() + .toEntity(BookView.class); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java new file mode 100644 index 0000000..7f4149d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java @@ -0,0 +1,32 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.support.PostgresTest; +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; + +@DataJpaTest +class ShelfTest extends PostgresTest { + + @Autowired + BookRepository books; + + @Test + void shelfListsBooksInTheOrderTheyWereAdded() { + Book beloved = books.save(new Book("Beloved", Format.PAPERBACK, "fiction")); + books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction")); + books.save(new Book("Rebecca", Format.EBOOK, "fiction")); + books.save(new Book("Ariel", Format.PAPERBACK, "poetry")); + + // An UPDATE. Postgres writes the new version of the row after the others, so a query + // without ORDER BY now returns Beloved last. H2 would still return it first. + beloved.rate(new BigDecimal("4.5")); + + assertThat(books.findByShelf("fiction")) + .extracting(Book::getTitle) + .containsExactly("Beloved", "Middlemarch", "Rebecca"); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Check.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Check.java new file mode 100644 index 0000000..8969583 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Check.java @@ -0,0 +1,131 @@ +package com.amigoscode.realdb.check; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import java.io.OutputStream; +import java.io.PrintStream; +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 acceptance checks that belong to one task and prints one line per criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same checks the usual Maven way.) + * + *

Two kinds of check live in this package. "Production: ..." runs the code in src/main against the + * checks' own Postgres. "Your suite: ..." runs YOUR tests (everything under src/test/java outside this + * package) through the JUnit launcher, sometimes with a bug put back in, and looks at what they did. + */ +public final class Check { + + /** Tasks that have checks. Task 8 is an inspection task with nothing to run: you answer questions. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: your test suite is green (passes from the start, must end green)"); + TASKS.put("1", "Task 1: See it break: H2 and Postgres disagree"); + TASKS.put("2", "Task 2: Run the repository tests on Postgres, fix what they find"); + TASKS.put("3", "Task 3: Inspect what @DataJpaTest does with your database"); + TASKS.put("4", "Task 4: Replace the fake where it hides the SQL"); + TASKS.put("5", "Task 5: One container, one context per kind of test"); + TASKS.put("6", "Task 6: Tests that own their data"); + TASKS.put("7", "Task 7: Order you can rely on"); + } + + /** The terminal. While the checks run, System.out goes nowhere: Spring and Hibernate print too much. */ + private static final PrintStream OUT = System.out; + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + 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])) { + OUT.println(); + OUT.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + OUT.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + OUT.println(); + return; + } + + boolean allGreen = true; + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + 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(); + OUT.println(); + OUT.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + OUT.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + OUT.println(); + OUT.flush(); + StudentSuite.shutDown(); + 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++; + OUT.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + OUT.println(" [PASS] " + test.getDisplayName()); + } else { + 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 -> OUT.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java new file mode 100644 index 0000000..a170cab --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java @@ -0,0 +1,35 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.CheckPostgres; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** Task 3. Passes from the start: Spring Boot 4 does not replace a @ServiceConnection container. */ +@Tag("task3") +@DataJpaTest(properties = "spring.main.banner-mode=off") +class DataJpaTestKeepsAServiceConnectionIT { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = CheckPostgres.container(); + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: a @ServiceConnection container is kept, with no extra annotation: the test runs on Postgres") + void keptPostgres() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java new file mode 100644 index 0000000..05aaefd --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java @@ -0,0 +1,38 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.UrlFromProperties; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; + +/** + * Task 3. Passes from the start: it documents what Spring Boot 4 does. The URL points at a real + * Postgres, but it comes from an ordinary property source, and H2 is on the classpath, so + * @DataJpaTest swaps the DataSource for an embedded H2. (Flyway is off because the real migrations + * cannot run on H2.) + */ +@Tag("task3") +@DataJpaTest(showSql = false, properties = {"spring.flyway.enabled=false", "spring.main.banner-mode=off"}) +@ContextConfiguration(initializers = UrlFromProperties.class) +class DataJpaTestReplacesYourDatabaseIT { + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: a datasource URL from application.properties is swapped for an embedded H2") + void swappedForH2() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("H2"); + assertThat(connection.getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java new file mode 100644 index 0000000..288a9dd --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java @@ -0,0 +1,34 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.UrlFromProperties; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; +import org.springframework.test.context.ContextConfiguration; + +/** Task 3. Passes from the start: the same URL as DataJpaTestReplacesYourDatabaseIT, kept this time. */ +@Tag("task3") +@DataJpaTest(properties = "spring.main.banner-mode=off") +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@ContextConfiguration(initializers = UrlFromProperties.class) +class DataJpaTestWithReplaceNoneIT { + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: with @AutoConfigureTestDatabase(replace = NONE) the same URL is kept: the test runs on Postgres") + void keptPostgres() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Db.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Db.java new file mode 100644 index 0000000..2a0722b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Db.java @@ -0,0 +1,47 @@ +package com.amigoscode.realdb.check; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +/** The "production" Postgres from compose.yaml. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5456/shop"); + static final String USER = env("DB_USER", "shop"); + static final String PASSWORD = env("DB_PASSWORD", "shop"); + + private Db() { + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = DriverManager.getConnection(URL, USER, PASSWORD)) { + 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; + } + } + + /** Drops every table, so the application's Flyway migrations build the schema from scratch. */ + static void empty() throws SQLException { + try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); + Statement statement = connection.createStatement()) { + statement.execute("drop schema public cascade"); + statement.execute("create schema public"); + } + } + + 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/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Demo.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Demo.java new file mode 100644 index 0000000..f3ec54c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Demo.java @@ -0,0 +1,202 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.RealDatabaseApplication; +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.CatalogueService; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.subscription.SubscriptionService; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs your test suite, then the same four features in "production": the code in src/main, on the + * Postgres from compose.yaml, with the schema built by the Flyway migrations. Run it with ./demo + * (or .\demo on Windows). + */ +public final class Demo { + + /** One feature, tried in production. */ + private record Scenario(String name, boolean ok, List lines) { + } + + public static void main(String[] args) throws Exception { + show(args); + // The Spring contexts of your tests are still cached, with their threads: end the JVM here. + StudentSuite.shutDown(); + System.exit(0); + } + + private static void show(String[] args) throws Exception { + if (args.length > 0) { + System.out.println("Usage: ./demo (Windows: .\\demo)"); + System.out.println(); + System.out.println("Runs your test suite, then the same features on real Postgres (docker compose up -d first)."); + return; + } + if (!Db.isUp()) { + return; + } + + System.out.println(); + System.out.println("1. YOUR TEST SUITE (src/test/java, everything outside check/)"); + System.out.println(); + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + Report.tests(run, "[GREEN]", "[RED] "); + System.out.println(); + System.out.println(" " + run.tests().size() + " tests: " + run.passedCount() + " green, " + + run.failed().size() + " red, in " + run.millis() + " ms. The database each test class used:"); + System.out.println(); + Report.databases(run); + + Db.empty(); + SpringApplication app = new SpringApplication(RealDatabaseApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + List scenarios = new ArrayList<>(); + String migrations; + String version; + try (ConfigurableApplicationContext context = app.run("--spring.main.web-application-type=none")) { + JdbcTemplate jdbc = context.getBean(JdbcTemplate.class); + CatalogueService catalogue = context.getBean(CatalogueService.class); + SubscriptionService subscriptions = context.getBean(SubscriptionService.class); + version = jdbc.queryForObject("show server_version", String.class).split(" ")[0]; + migrations = jdbc.queryForList("select 'V' || version || ' ' || description from flyway_schema_history" + + " where success order by installed_rank", String.class).stream().collect(Collectors.joining(", ")); + scenarios.add(topRated(catalogue)); + scenarios.add(audiobook(catalogue)); + scenarios.add(subscribeTwice(subscriptions, jdbc)); + scenarios.add(shelf(catalogue)); + } + + System.out.println(); + System.out.println("2. PRODUCTION: the same features, the code in src/main, on PostgreSQL " + version); + System.out.println(" (compose.yaml, " + Db.URL + "), schema from Flyway: " + migrations); + System.out.println(); + for (Scenario scenario : scenarios) { + System.out.println(" " + (scenario.ok() ? "[OK] " : "[BROKEN]") + " " + scenario.name()); + for (String line : scenario.lines()) { + System.out.println(" " + line); + } + } + + long broken = scenarios.stream().filter(scenario -> !scenario.ok()).count(); + System.out.println(); + if (run.allPassed() && broken > 0) { + System.out.println("RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. " + run.passedCount() + " of " + + run.tests().size() + " tests pass, and " + broken + " of " + scenarios.size() + + " features are broken on Postgres."); + } else if (broken > 0) { + System.out.println("RESULT: BROKEN, AND YOUR TESTS SEE IT. " + run.failed().size() + " of " + run.tests().size() + + " tests fail, and " + broken + " of " + scenarios.size() + " features are broken on Postgres."); + } else if (!run.allPassed()) { + System.out.println("RESULT: PRODUCTION WORKS, BUT " + run.failed().size() + " OF " + run.tests().size() + + " TESTS FAIL. A red test on working code is a test to fix."); + } else { + System.out.println("RESULT: OK. All " + run.tests().size() + " tests pass, and all " + scenarios.size() + + " features work on Postgres."); + } + System.out.println(); + } + + private static Scenario topRated(CatalogueService catalogue) { + try { + rated(catalogue, "Dune", "4.8"); + rated(catalogue, "Emma", "3.9"); + catalogue.addBook("No Reviews Yet", Format.PAPERBACK, "fiction"); + rated(catalogue, "Hamlet", "4.2"); + List top = catalogue.topRated(); + boolean ok = true; + boolean unratedSeen = false; + for (Book book : top) { + unratedSeen |= book.getRating() == null; + ok &= book.getRating() == null || !unratedSeen; + } + List lines = new ArrayList<>(); + lines.add("added: Dune 4.8, Emma 3.9, No Reviews Yet (no rating), Hamlet 4.2"); + lines.add("top 3: " + describe(top)); + if (!ok) { + lines.add("A book nobody has reviewed is ahead of the best rated ones."); + } + return new Scenario("Top rated", ok, lines); + } catch (RuntimeException e) { + return new Scenario("Top rated", false, List.of(error(e))); + } + } + + private static Scenario audiobook(CatalogueService catalogue) { + try { + Book book = catalogue.addBook("Dune", Format.AUDIOBOOK, "audio"); + return new Scenario("Add an audiobook", true, List.of("saved: " + book.getTitle() + " (" + book.getFormat() + "), id " + book.getId())); + } catch (RuntimeException e) { + return new Scenario("Add an audiobook", false, List.of(error(e))); + } + } + + private static Scenario subscribeTwice(SubscriptionService subscriptions, JdbcTemplate jdbc) { + String name = "Subscribe ann@example.com, then Ann@Example.COM"; + try { + SubscriptionService.Outcome first = subscriptions.subscribe("ann@example.com"); + SubscriptionService.Outcome second = subscriptions.subscribe("Ann@Example.COM"); + int rows = jdbc.queryForObject("select count(*) from subscriber", Integer.class); + boolean ok = first == SubscriptionService.Outcome.SUBSCRIBED + && second == SubscriptionService.Outcome.ALREADY_SUBSCRIBED && rows == 1; + return new Scenario(name, ok, List.of(first + ", then " + second + ". Rows in subscriber: " + rows)); + } catch (RuntimeException e) { + return new Scenario(name, false, List.of(error(e))); + } + } + + private static Scenario shelf(CatalogueService catalogue) { + String name = "Shelf \"classics\" after a review of Beloved"; + try { + Book beloved = catalogue.addBook("Beloved", Format.PAPERBACK, "classics"); + catalogue.addBook("Middlemarch", Format.HARDCOVER, "classics"); + catalogue.addBook("Rebecca", Format.EBOOK, "classics"); + catalogue.rate(beloved.getId(), new BigDecimal("4.5")); + List shelf = catalogue.shelf("classics"); + List titles = shelf.stream().map(Book::getTitle).toList(); + boolean ok = titles.equals(List.of("Beloved", "Middlemarch", "Rebecca")); + List lines = new ArrayList<>(); + lines.add("added: Beloved, Middlemarch, Rebecca. Then Beloved got a rating."); + lines.add("listed: " + String.join(", ", titles)); + if (!ok) { + lines.add("Not the order they were added in."); + } + return new Scenario(name, ok, lines); + } catch (RuntimeException e) { + return new Scenario(name, false, List.of(error(e))); + } + } + + private static void rated(CatalogueService catalogue, String title, String rating) { + Book book = catalogue.addBook(title, Format.PAPERBACK, "fiction"); + catalogue.rate(book.getId(), new BigDecimal(rating)); + } + + private static String describe(List books) { + return books.stream() + .map(book -> book.getTitle() + (book.getRating() == null ? " (no rating)" : " " + book.getRating())) + .collect(Collectors.joining(", ")); + } + + /** The database's own words: the first line of the deepest cause. */ + private static String error(Throwable throwable) { + Throwable deepest = throwable; + while (deepest.getCause() != null && deepest.getCause() != deepest) { + deepest = deepest.getCause(); + } + String message = deepest.getMessage() == null ? deepest.getClass().getSimpleName() : deepest.getMessage(); + return Report.shorten(message.lines().findFirst().orElse(message), 150); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java new file mode 100644 index 0000000..cbbb2f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java @@ -0,0 +1,94 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.realdb.check.support.CheckPostgres; +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; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. These pass from the start: they pin down, with plain SQL, the differences between H2 and + * Postgres that the bugs in this project hide behind. Same statements, two databases. + */ +@Tag("task1") +class H2VersusPostgresIT { + + private static final String H2_POSTGRES_MODE = "jdbc:h2:mem:%s;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE"; + + @Test + @DisplayName("H2 vs Postgres: ORDER BY rating DESC puts the NULL rating last on H2 (PostgreSQL mode), first on Postgres") + void nullsInDescendingOrder() throws SQLException { + String[] setup = { + "create table book (id int primary key, title text, rating numeric(2,1))", + "insert into book values (1, 'Dune', 4.8), (2, 'No Reviews Yet', null), (3, 'Emma', 3.9)"}; + String query = "select title from book order by rating desc"; + + try (Connection h2 = h2("nulls"); Connection postgres = CheckPostgres.newDatabase("nulls")) { + assertThat(titles(h2, setup, query)).containsExactly("Dune", "Emma", "No Reviews Yet"); + assertThat(titles(postgres, setup, query)).containsExactly("No Reviews Yet", "Dune", "Emma"); + } + } + + @Test + @DisplayName("H2 vs Postgres: without ORDER BY, H2 returns rows by primary key, Postgres returns the row you just updated last") + void orderWithoutOrderBy() throws SQLException { + String[] setup = { + "create table book (id int primary key, title text, rating numeric(2,1))", + "insert into book values (1, 'Beloved', null), (2, 'Middlemarch', null), (3, 'Rebecca', null)", + "update book set rating = 4.5 where id = 1"}; + String query = "select title from book"; + + try (Connection h2 = h2("order"); Connection postgres = CheckPostgres.newDatabase("unordered")) { + assertThat(titles(h2, setup, query)).containsExactly("Beloved", "Middlemarch", "Rebecca"); + assertThat(titles(postgres, setup, query)).containsExactly("Middlemarch", "Rebecca", "Beloved"); + } + } + + @Test + @DisplayName("H2 vs Postgres: H2 cannot parse the real schema's index on lower(email) or ON CONFLICT (email); Postgres can, and rejects ON CONFLICT (email) because no index matches it") + void theRealSchemaAndTheUpsert() throws SQLException { + String table = "create table subscriber (id int generated by default as identity primary key, email text not null)"; + String index = "create unique index subscriber_email_key on subscriber (lower(email))"; + String upsert = "insert into subscriber (email) values ('ann@example.com') on conflict (email) do nothing"; + + try (Connection h2 = h2("schema"); Statement statement = h2.createStatement()) { + statement.execute(table); + assertThatThrownBy(() -> statement.execute(index)).hasMessageContaining("Syntax error"); + assertThatThrownBy(() -> statement.execute(upsert)).hasMessageContaining("Syntax error"); + } + try (Connection postgres = CheckPostgres.newDatabase("upsert"); Statement statement = postgres.createStatement()) { + statement.execute(table); + statement.execute(index); + assertThatThrownBy(() -> statement.execute(upsert)) + .hasMessageContaining("there is no unique or exclusion constraint matching the ON CONFLICT specification"); + } + } + + private static Connection h2(String name) throws SQLException { + return DriverManager.getConnection(H2_POSTGRES_MODE.formatted(name), "sa", ""); + } + + private static List titles(Connection connection, String[] setup, String query) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String sql : setup) { + statement.execute(sql); + } + List titles = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery(query)) { + while (rows.next()) { + titles.add(rows.getString(1)); + } + } + return titles; + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Inspect.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Inspect.java new file mode 100644 index 0000000..4059338 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Inspect.java @@ -0,0 +1,138 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.Recording.ContextInfo; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.sql.DataSource; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs your test suite once with a recorder attached and shows what it did underneath: the database + * each test class talked to, where its schema came from, how many Postgres containers and Spring + * contexts were started and how long each context took, and the rows left behind. Run it with + * ./inspect (or .\inspect on Windows). Needs Docker once your tests use Testcontainers. + */ +public final class Inspect { + + public static void main(String[] args) { + show(args); + // The Spring contexts of your tests are still cached, with their threads: end the JVM here. + StudentSuite.shutDown(); + System.exit(0); + } + + private static void show(String[] args) { + if (args.length > 0) { + System.out.println("Usage: ./inspect (Windows: .\\inspect)"); + System.out.println(); + System.out.println("Runs your test suite once and shows which databases, containers and Spring contexts it used."); + return; + } + String startedAt = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + List contexts = Recording.contexts(); + + System.out.println(); + System.out.println("TESTS (suite started at " + startedAt + ", took " + run.millis() + " ms)"); + Report.tests(run, "[PASS]", "[FAIL]"); + System.out.println(" " + run.tests().size() + " tests, " + run.passedCount() + " pass, " + run.failed().size() + " fail"); + + System.out.println(); + System.out.println("DATABASE EACH TEST CLASS USED"); + Report.databases(run); + + System.out.println(); + System.out.println("WHERE EACH SCHEMA CAME FROM"); + if (contexts.isEmpty()) { + System.out.println(" none of your tests started Spring"); + } + for (ContextInfo context : contexts) { + System.out.println(" context " + context.number + ": " + schema(context)); + } + + System.out.println(); + Map> servers = new LinkedHashMap<>(); + contexts.stream().filter(context -> context.database.serverId() != null) + .forEach(context -> servers.computeIfAbsent(context.database.serverId(), id -> new ArrayList<>()).add(context)); + System.out.println("POSTGRES SERVERS (one per container): " + servers.size()); + if (!servers.isEmpty()) { + List rows = new ArrayList<>(); + rows.add(new String[] {"server id", "started at", "used by contexts"}); + servers.forEach((id, users) -> rows.add(new String[] {id, users.get(0).database.serverStartedAt(), + users.stream().map(context -> String.valueOf(context.number)).collect(Collectors.joining(", "))})); + Report.table(rows); + } + + System.out.println(); + System.out.println("SPRING CONTEXTS STARTED: " + contexts.size()); + if (!contexts.isEmpty()) { + List rows = new ArrayList<>(); + rows.add(new String[] {"#", "kind", "start-up", "used by"}); + for (ContextInfo context : contexts) { + rows.add(new String[] {String.valueOf(context.number), context.kind, + String.format("%,d ms", context.loadMillis), + context.testClasses.stream().map(Class::getSimpleName).collect(Collectors.joining(", "))}); + } + Report.table(rows); + } + + System.out.println(); + System.out.println("ROWS LEFT BEHIND AFTER THE LAST TEST"); + List rows = new ArrayList<>(); + rows.add(new String[] {"context", "database", "book", "subscriber"}); + for (ContextInfo context : contexts) { + rows.add(leftBehind(context)); + } + if (rows.size() > 1) { + Report.table(rows); + } else { + System.out.println(" no database"); + } + System.out.println(); + } + + private static String schema(ContextInfo context) { + if (!context.isActive()) { + return "unknown: the context was closed (@DirtiesContext), its database with it"; + } + DataSource dataSource = context.dataSource(); + if (dataSource == null) { + return "no DataSource"; + } + if (!context.database.flywaySchema()) { + return "made up by Hibernate from the entities (no flyway_schema_history table)"; + } + List applied = new JdbcTemplate(dataSource).queryForList( + "select 'V' || version || ' ' || description from flyway_schema_history where success order by installed_rank", + String.class); + return "Flyway migrations " + String.join(", ", applied); + } + + private static String[] leftBehind(ContextInfo context) { + String database = Report.product(context.database); + if (!context.isActive()) { + return new String[] {String.valueOf(context.number), database, "gone", "(context closed)"}; + } + JdbcTemplate jdbc = new JdbcTemplate(context.dataSource()); + return new String[] {String.valueOf(context.number), database, count(jdbc, "book"), count(jdbc, "subscriber")}; + } + + private static String count(JdbcTemplate jdbc, String table) { + try { + return String.valueOf(jdbc.queryForObject("select count(*) from " + table, Long.class)); + } catch (RuntimeException e) { + return "no table"; + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/IsolationIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/IsolationIT.java new file mode 100644 index 0000000..88c9c69 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/IsolationIT.java @@ -0,0 +1,59 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.YourSuite; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 6: every test owns its data. Order, company and the value of a generated id do not matter. */ +@Tag("task6") +class IsolationIT { + + @Test + @DisplayName("Your suite: every test that passes in the full run also passes when it runs on its own") + void eachTestAlone() { + List broken = YourSuite.brokenBy(StudentSuite.eachAlone()); + if (!broken.isEmpty()) { + fail("These tests pass in the full run and fail on their own. They depend on what ran before them:" + + " data another test created, or rows nobody cleaned up:\n" + + String.join("\n", broken)); + } + } + + @Test + @DisplayName("Your suite: every test gives the same result with classes and methods run from Z to A") + void reverseOrder() { + Map reversed = YourSuite.byName(StudentSuite.run(Variant.REVERSED)); + List different = new ArrayList<>(); + for (TestResult test : StudentSuite.run(Variant.AS_IS).tests()) { + TestResult other = reversed.get(test.name()); + if (other != null && other.passed() != test.passed()) { + different.add(test.name() + (test.passed() ? " passes A to Z, fails Z to A: " + other.failure() + : " fails A to Z, passes Z to A: " + test.failure())); + } + } + if (!different.isEmpty()) { + fail("The order changes the result. Some test leaves data behind that another one trips over:\n" + + String.join("\n", different)); + } + } + + @Test + @DisplayName("Your suite: no test depends on the value of a generated id (every sequence moved on by 1000 before each test)") + void noGeneratedIdValues() { + List broken = YourSuite.brokenBy(YourSuite.byName(StudentSuite.run(Variant.SHIFTED_IDS))); + if (!broken.isEmpty()) { + fail("These tests pass in the first run and fail in this one:\n" + String.join("\n", broken) + + "\nA test that expects a literal id fails here: assert on the id the code gave back." + + " So does a test that trips over rows earlier runs left behind."); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java new file mode 100644 index 0000000..f037366 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.Recording.ContextInfo; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.YourSuite; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 5: one Postgres container and as few Spring contexts as possible for the whole suite. Counted, + * not timed: the probe records every context your suite starts and the Postgres server behind it. + */ +@Tag("task5") +class OneContainerIT { + + @BeforeEach + void runYourSuite() { + StudentSuite.run(Variant.AS_IS); + } + + @Test + @DisplayName("Your suite: every Spring test runs on PostgreSQL (no H2 left)") + void everySpringTestOnPostgres() { + List notPostgres = Recording.classes().entrySet().stream() + .filter(entry -> !entry.getValue().database.isPostgres()) + .map(entry -> entry.getKey().getSimpleName() + ": " + entry.getValue().database.describe()) + .toList(); + if (Recording.classes().isEmpty()) { + fail("None of your tests started Spring, so none of them ran on a database."); + } + if (!notPostgres.isEmpty()) { + fail("These test classes do not run on PostgreSQL:\n" + String.join("\n", notPostgres)); + } + } + + @Test + @DisplayName("Your suite: one Postgres container for the whole run, shared by every test class") + void oneContainer() { + List servers = Recording.contexts().stream() + .map(context -> context.database.serverId()) + .filter(Objects::nonNull) + .distinct() + .toList(); + if (servers.size() != 1) { + fail("Your tests talked to " + servers.size() + " Postgres servers (containers). Expected exactly 1.\n" + + YourSuite.databases()); + } + } + + @Test + @DisplayName("Your suite: at most 2 Spring contexts, one per kind of test (@DataJpaTest, @SpringBootTest)") + void fewContexts() { + List contexts = Recording.contexts(); + if (contexts.size() > 2) { + fail(contexts.size() + " Spring contexts were started. Test classes of the same kind should share one:\n" + + contexts.stream() + .map(context -> "context " + context.number + " " + context.kind + ": " + + context.testClasses.stream().map(Class::getSimpleName).collect(Collectors.joining(", "))) + .collect(Collectors.joining("\n")) + + "\nLook for what differs: properties, @Import, @DirtiesContext, @MockitoBean, @ActiveProfiles, the container."); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Report.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Report.java new file mode 100644 index 0000000..dd75be1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/Report.java @@ -0,0 +1,100 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.test.context.BootstrapWith; + +/** Printing shared by ./demo and ./inspect. Plain ASCII, so it looks the same in every terminal. */ +final class Report { + + private Report() { + } + + static void tests(Run run, String green, String red) { + for (TestResult test : run.tests()) { + System.out.println(" " + (test.passed() ? green : red) + " " + test.name()); + if (!test.passed()) { + System.out.println(" " + shorten(test.failure(), 150)); + } + } + } + + /** One row per test class: the database it talked to, or that it started no Spring at all. */ + static void databases(Run run) { + Map, Recording.ContextInfo> spring = Recording.classes(); + Set classes = new LinkedHashSet<>(); + run.tests().forEach(test -> classes.add(test.className())); + List rows = new ArrayList<>(); + rows.add(new String[] {"test class", "database", "url"}); + for (String className : classes) { + String simple = className.substring(className.lastIndexOf('.') + 1); + Recording.ContextInfo context = spring.entrySet().stream() + .filter(entry -> entry.getKey().getName().equals(className)) + .map(Map.Entry::getValue) + .findFirst().orElse(null); + if (context == null && isSpringTest(className)) { + rows.add(new String[] {simple, "none", "its Spring context did not start (see the failure above)"}); + } else if (context == null) { + rows.add(new String[] {simple, "none", "no Spring context: a plain unit test"}); + } else { + rows.add(new String[] {simple, product(context.database), context.database.url()}); + } + } + table(rows); + } + + private static boolean isSpringTest(String className) { + try { + Class type = Class.forName(className); + return MergedAnnotations.from(type, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).isPresent(BootstrapWith.class); + } catch (ClassNotFoundException | LinkageError e) { + return false; + } + } + + static String product(Recording.DatabaseInfo database) { + if (database.product().equals("none")) { + return "no DataSource"; + } + String version = database.version().split(" ")[0]; + return database.product() + " " + version; + } + + static void table(List rows) { + 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()); + } + } + } + + static String shorten(String text, int max) { + if (text == null) { + return ""; + } + String ascii = text.replaceAll("[^\\x20-\\x7E]", "?"); + return ascii.length() <= max ? ascii : ascii.substring(0, max) + "..."; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java new file mode 100644 index 0000000..85f61f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import java.math.BigDecimal; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 7: an order you rely on is an ORDER BY you wrote, and a test that would notice without it. */ +@Tag("task7") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class ShelfOrderIT extends ProductionTest { + + @Test + @DisplayName("Production: a shelf lists its books in the order they were added, also after one of them is updated (on Postgres)") + void shelfOrderAfterAnUpdate() { + Book beloved = catalogue.addBook("Beloved", Format.PAPERBACK, "fiction"); + catalogue.addBook("Middlemarch", Format.HARDCOVER, "fiction"); + catalogue.addBook("Rebecca", Format.EBOOK, "fiction"); + catalogue.rate(beloved.getId(), new BigDecimal("4.5")); + + assertThat(titles(catalogue.shelf("fiction"))).containsExactly("Beloved", "Middlemarch", "Rebecca"); + } + + @Test + @DisplayName("Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY)") + void catchesTheMissingOrderBy() { + YourSuite.catches(Variant.SHELF_ORDER_BUG, + "On Postgres, update one of the books (rate it) before you read the shelf, and assert on the order."); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java new file mode 100644 index 0000000..aadcb30 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java @@ -0,0 +1,59 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import com.amigoscode.realdb.subscription.SubscriptionService.Outcome; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 4: the SQL behind subscribe is tested on Postgres, the service's logic keeps its fake. */ +@Tag("task4") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class SubscriptionIT extends ProductionTest { + + @Test + @DisplayName("Production: subscribing ann@example.com, then Ann@Example.COM, keeps one subscriber and answers ALREADY_SUBSCRIBED (on Postgres)") + void subscribeTwice() { + Outcome first = expectNoError("Subscribing ann@example.com", () -> subscriptions.subscribe("ann@example.com")); + Outcome second = expectNoError("Subscribing Ann@Example.COM", () -> subscriptions.subscribe("Ann@Example.COM")); + + assertThat(first).isEqualTo(Outcome.SUBSCRIBED); + assertThat(second).isEqualTo(Outcome.ALREADY_SUBSCRIBED); + assertThat(jdbc.queryForObject("select count(*) from subscriber", Integer.class)).isEqualTo(1); + } + + @Test + @DisplayName("Your suite: catches the ON CONFLICT bug (a test fails when subscribe uses ON CONFLICT (email))") + void catchesTheOnConflictBug() { + YourSuite.catches(Variant.ON_CONFLICT_BUG, + "Call SubscriberRepository.subscribe in a test that runs on Postgres with the Flyway schema." + + " The fake in SubscriptionServiceTest never runs the SQL."); + } + + @Test + @DisplayName("Your suite: SubscriptionServiceTest still tests the service's logic with the fake, with no Spring and no database") + void theFakeStaysForTheLogic() { + List tests = StudentSuite.run(Variant.AS_IS).tests().stream() + .filter(test -> test.simpleClassName().equals("SubscriptionServiceTest")) + .toList(); + if (tests.isEmpty()) { + fail("SubscriptionServiceTest is gone. Keep it: a fake is the right tool for the service's own logic" + + " (the email check, what 0 rows means). Only the SQL needs the database."); + } + assertThat(tests).as("SubscriptionServiceTest results").allMatch(TestResult::passed); + boolean startedSpring = Recording.classes().keySet().stream() + .anyMatch(type -> type.getSimpleName().equals("SubscriptionServiceTest")); + assertThat(startedSpring).as("SubscriptionServiceTest started a Spring context").isFalse(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java new file mode 100644 index 0000000..158ee8d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java @@ -0,0 +1,84 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 2: the repository tests run on Postgres, and the two bugs they find are fixed. */ +@Tag("task2") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class TopRatedAndAudiobookIT extends ProductionTest { + + @Test + @DisplayName("Production: top rated lists the best rated books first, and never an unrated book ahead of a rated one (on Postgres)") + void topRated() { + rated("Dune", "4.8"); + catalogue.addBook("No Reviews Yet", Format.PAPERBACK, "fiction"); + rated("Emma", "3.9"); + catalogue.addBook("Brand New", Format.EBOOK, "fiction"); + rated("Hamlet", "4.2"); + + List top = catalogue.topRated(); + + assertThat(titles(top)).as("top rated").startsWith("Dune", "Hamlet", "Emma"); + } + + @Test + @DisplayName("Production: an AUDIOBOOK can be added (on Postgres, with the Flyway migrations)") + void audiobook() { + expectNoError("Adding an AUDIOBOOK", () -> catalogue.addBook("Dune", Format.AUDIOBOOK, "fiction")); + + assertThat(jdbc.queryForObject("select count(*) from book where format = 'AUDIOBOOK'", Integer.class)).isEqualTo(1); + } + + @Test + @DisplayName("Your suite: BookRepositoryTest runs on PostgreSQL, not H2") + void bookRepositoryTestOnPostgres() { + Recording.DatabaseInfo database = YourSuite.databaseOf("BookRepositoryTest"); + if (!database.isPostgres()) { + fail("BookRepositoryTest ran on " + database.describe()); + } + } + + @Test + @DisplayName("Your suite: BookRepositoryTest's schema comes from the Flyway migrations, not from Hibernate") + void bookRepositoryTestUsesTheMigrations() { + Recording.DatabaseInfo database = YourSuite.databaseOf("BookRepositoryTest"); + if (!database.flywaySchema()) { + fail("BookRepositoryTest's database has no flyway_schema_history table: Hibernate made the schema up" + + " from the entities.\nDatabase: " + database.describe()); + } + } + + @Test + @DisplayName("Your suite: catches the top rated bug (a test fails when findTopRated has no NULLS LAST)") + void catchesTheTopRatedBug() { + YourSuite.catches(Variant.TOP_RATED_BUG, + "Save a book without a rating next to rated ones, and assert on the order findTopRated returns, on Postgres."); + } + + @Test + @DisplayName("Your suite: catches the missing migration (a test fails when the database rejects AUDIOBOOK)") + void catchesTheMissingMigration() { + YourSuite.catches(Variant.MISSING_MIGRATION_BUG, + "Save an AUDIOBOOK in a test that runs on Postgres with the Flyway schema."); + } + + private void rated(String title, String rating) { + Book book = catalogue.addBook(title, Format.PAPERBACK, "fiction"); + catalogue.rate(book.getId(), new BigDecimal(rating)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java new file mode 100644 index 0000000..afa55cf --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java @@ -0,0 +1,24 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline. Your suite must be green on the code as it is: start/ is, and solution/ is. */ +@Tag("baseline") +class YourSuiteIT { + + @Test + @DisplayName("Your suite: every test passes on the code as it is") + void everyTestPasses() { + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + if (!run.allPassed()) { + fail(run.failed().size() + " of " + run.tests().size() + " tests fail:\n" + + String.join("\n", run.failed().stream().map(test -> test.name() + ": " + test.failure()).toList())); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java new file mode 100644 index 0000000..1fd6a7f --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java @@ -0,0 +1,85 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import javax.sql.DataSource; + +/** + * A bug from start/, put back into the fixed code while your test suite runs. A good suite fails when + * one of these is switched on: it "catches" the bug. Only the checks switch them on, never your + * normal test runs. + * + *

Three of them replace one repository method (see {@link MutantPostProcessor}). The fourth puts + * the database back the way it was before V2__allow_audiobooks.sql: it adds a constraint that rejects + * AUDIOBOOK, but only in a database whose schema was built by Flyway. A schema that Hibernate made up + * for H2 never had the migration in the first place. + */ +public enum Mutant { + + TOP_RATED("BookRepository.findTopRated without NULLS LAST: unrated books come first on Postgres"), + MISSING_MIGRATION("V2__allow_audiobooks.sql removed: the database rejects AUDIOBOOK"), + ON_CONFLICT("SubscriberRepository.subscribe with ON CONFLICT (email): no index matches it"), + SHELF_ORDER("BookRepository.findByShelf without ORDER BY: the database picks the order"); + + private static final String CONSTRAINT = "realdb_check_no_audiobook"; + + private static volatile Mutant active; + private static final Set CHANGED = Collections.newSetFromMap(new IdentityHashMap<>()); + + private final String description; + + Mutant(String description) { + this.description = description; + } + + public String description() { + return description; + } + + static Mutant active() { + return active; + } + + static void activate(Mutant mutant) { + active = mutant; + } + + /** Switches every mutant off and puts back any database that was changed. */ + static synchronized void deactivate() { + active = null; + for (DataSource dataSource : CHANGED) { + run(dataSource, "alter table book drop constraint if exists " + CONSTRAINT); + } + CHANGED.clear(); + } + + /** Called before each test class: puts the database bug into this context's database if needed. */ + static synchronized void prepareDatabase(DataSource dataSource, Recording.DatabaseInfo database) { + if (active != MISSING_MIGRATION || dataSource == null || CHANGED.contains(dataSource)) { + return; + } + if (!database.isPostgres() || !database.flywaySchema()) { + return; + } + run(dataSource, "alter table book drop constraint if exists " + CONSTRAINT); + run(dataSource, "alter table book add constraint " + CONSTRAINT + " check (format <> 'AUDIOBOOK') not valid"); + CHANGED.add(dataSource); + } + + private static void run(DataSource dataSource, String sql) { + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + connection.setAutoCommit(true); + statement.execute("set lock_timeout = '5s'"); + try { + statement.execute(sql); + } finally { + statement.execute("reset lock_timeout"); + } + } catch (Exception e) { + // The database is gone (its context was closed) or has no book table: nothing to change. + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java new file mode 100644 index 0000000..b165e1c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.check.probe; + +import java.util.List; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ContextConfigurationAttributes; +import org.springframework.test.context.ContextCustomizer; +import org.springframework.test.context.ContextCustomizerFactory; +import org.springframework.test.context.MergedContextConfiguration; + +/** + * Registered in META-INF/spring.factories, so it takes part in every Spring test context. It adds + * {@link MutantPostProcessor} to the contexts of your tests (not to the checks' own contexts). It is + * the same for every test class, so it never stops two of your test classes from sharing a context. + */ +public class MutantContextCustomizerFactory implements ContextCustomizerFactory { + + @Override + public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { + return SuiteProbe.isYourTest(testClass) ? new Customizer() : null; + } + + private static final class Customizer implements ContextCustomizer { + + @Override + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { + context.getBeanFactory().addBeanPostProcessor(new MutantPostProcessor(context.getBeanFactory())); + } + + @Override + public boolean equals(Object other) { + return other instanceof Customizer; + } + + @Override + public int hashCode() { + return Customizer.class.hashCode(); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java new file mode 100644 index 0000000..e2523b1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java @@ -0,0 +1,75 @@ +package com.amigoscode.realdb.check.probe; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.BookRepository; +import com.amigoscode.realdb.subscription.SubscriberRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.TypedQuery; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import javax.sql.DataSource; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.data.domain.Limit; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.ClassUtils; + +/** + * Wraps BookRepository and SubscriberRepository in every Spring context your tests start. While no + * {@link Mutant} is switched on, every call goes straight through to the real repository. While one is + * on, the one method it names runs the query from start/ instead. + */ +final class MutantPostProcessor implements BeanPostProcessor { + + private final ConfigurableListableBeanFactory beanFactory; + + MutantPostProcessor(ConfigurableListableBeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + if (bean instanceof BookRepository || bean instanceof SubscriberRepository) { + return Proxy.newProxyInstance(bean.getClass().getClassLoader(), + ClassUtils.getAllInterfaces(bean), (proxy, method, args) -> invoke(bean, method, args)); + } + return bean; + } + + private Object invoke(Object repository, Method method, Object[] args) throws Throwable { + Mutant mutant = Mutant.active(); + if (mutant == Mutant.TOP_RATED && method.getName().equals("findTopRated") && repository instanceof BookRepository) { + TypedQuery query = entityManager().createQuery("select b from Book b order by b.rating desc", Book.class); + if (args != null && args.length == 1 && args[0] instanceof Limit limit && limit.isLimited()) { + query.setMaxResults(limit.max()); + } + return query.getResultList(); + } + if (mutant == Mutant.SHELF_ORDER && method.getName().equals("findByShelf") && repository instanceof BookRepository) { + return entityManager().createQuery("select b from Book b where b.shelf = :shelf", Book.class) + .setParameter("shelf", args[0]) + .getResultList(); + } + if (mutant == Mutant.ON_CONFLICT && method.getName().equals("subscribe") && repository instanceof SubscriberRepository) { + TransactionTemplate transaction = new TransactionTemplate(beanFactory.getBean(PlatformTransactionManager.class)); + JdbcTemplate jdbc = new JdbcTemplate(beanFactory.getBean(DataSource.class)); + Integer rows = transaction.execute(status -> jdbc.update( + "insert into subscriber (email) values (?) on conflict (email) do nothing", args[0])); + return rows; + } + try { + return method.invoke(repository, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + private EntityManager entityManager() { + return SharedEntityManagerCreator.createSharedEntityManager(beanFactory.getBean(EntityManagerFactory.class)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Recording.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Recording.java new file mode 100644 index 0000000..07819b1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/Recording.java @@ -0,0 +1,174 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.sql.DataSource; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * What the probe saw while your test suite ran: every Spring context it started, how long that took, + * and which database each one was connected to. Filled by {@link SuiteProbe} during the first run of + * your suite in this JVM, read by the checks and by ./inspect. + */ +public final class Recording { + + /** One Spring application context that your tests used. */ + public static final class ContextInfo { + + public final int number; + public final String kind; + public final long loadMillis; + public final DatabaseInfo database; + public final List> testClasses = new ArrayList<>(); + final ApplicationContext context; + + ContextInfo(int number, String kind, long loadMillis, DatabaseInfo database, ApplicationContext context) { + this.number = number; + this.kind = kind; + this.loadMillis = loadMillis; + this.database = database; + this.context = context; + } + + public boolean isActive() { + return !(context instanceof ConfigurableApplicationContext configurable) || configurable.isActive(); + } + + public DataSource dataSource() { + return context.getBeanProvider(DataSource.class).getIfUnique(); + } + } + + /** + * The database behind a context's DataSource. {@code serverId} is Postgres's system identifier: every + * Postgres server (every container) has a different one. + */ + public record DatabaseInfo(String product, String version, String url, String serverId, String serverStartedAt, + boolean flywaySchema) { + + static final DatabaseInfo NONE = new DatabaseInfo("none", "", "", null, null, false); + + public boolean isPostgres() { + return product.equalsIgnoreCase("PostgreSQL"); + } + + public boolean isH2() { + return product.equalsIgnoreCase("H2"); + } + + public String describe() { + if (this == NONE) { + return "no DataSource"; + } + String name = isPostgres() ? "PostgreSQL " + version.split(" ")[0] : product + " " + version.split(" ")[0]; + return name + " " + url; + } + } + + private static volatile boolean active; + private static final Map CONTEXTS = new IdentityHashMap<>(); + private static final Map, ContextInfo> CLASSES = new LinkedHashMap<>(); + private static final Map DESCRIBED = new IdentityHashMap<>(); + + private Recording() { + } + + static boolean isActive() { + return active; + } + + static synchronized void start() { + CONTEXTS.clear(); + CLASSES.clear(); + active = true; + } + + static synchronized void stop() { + active = false; + } + + /** Called for every test instance. The first time a context is seen, the call to getApplicationContext loads it. */ + static synchronized ContextInfo seen(Class testClass, String kind, ApplicationContext context, long loadMillis) { + ContextInfo info = CONTEXTS.get(context); + if (info == null) { + info = new ContextInfo(CONTEXTS.size() + 1, kind, loadMillis, describeOnce(context), context); + CONTEXTS.put(context, info); + } + if (!CLASSES.containsKey(testClass)) { + CLASSES.put(testClass, info); + info.testClasses.add(testClass); + } + return info; + } + + /** Closes every context your tests used, in any run, so nothing is left to close at JVM exit. */ + static synchronized void closeAll() { + for (ApplicationContext context : DESCRIBED.keySet()) { + if (context instanceof ConfigurableApplicationContext configurable && configurable.isActive()) { + try { + configurable.close(); + } catch (RuntimeException e) { + // Closing is tidying up: nothing to report. + } + } + } + } + + /** The database behind a context, looked up once per context. */ + static synchronized DatabaseInfo describeOnce(ApplicationContext context) { + return DESCRIBED.computeIfAbsent(context, Recording::describe); + } + + /** Every context your suite started, in the order they were started. */ + public static synchronized List contexts() { + List all = new ArrayList<>(CONTEXTS.values()); + all.sort((a, b) -> Integer.compare(a.number, b.number)); + return all; + } + + /** Which context each Spring test class used. Test classes without Spring are not in here. */ + public static synchronized Map, ContextInfo> classes() { + return new LinkedHashMap<>(CLASSES); + } + + private static DatabaseInfo describe(ApplicationContext context) { + DataSource dataSource = context.getBeanProvider(DataSource.class).getIfUnique(); + if (dataSource == null) { + return DatabaseInfo.NONE; + } + try (Connection connection = dataSource.getConnection()) { + var meta = connection.getMetaData(); + String product = meta.getDatabaseProductName(); + String serverId = null; + String startedAt = null; + if (product.equalsIgnoreCase("PostgreSQL")) { + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery(""" + select system_identifier::text, + to_char(pg_postmaster_start_time(), 'HH24:MI:SS.MS') + from pg_control_system()""")) { + rows.next(); + serverId = rows.getString(1); + startedAt = rows.getString(2); + } + } + boolean flyway; + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery( + "select count(*) from information_schema.tables where lower(table_name) = 'flyway_schema_history'")) { + rows.next(); + flyway = rows.getInt(1) > 0; + } + return new DatabaseInfo(product, meta.getDatabaseProductVersion(), meta.getURL(), serverId, startedAt, flyway); + } catch (Exception e) { + return new DatabaseInfo("unknown (" + e.getClass().getSimpleName() + ")", "", "", null, null, false); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java new file mode 100644 index 0000000..0144b6d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java @@ -0,0 +1,266 @@ +package com.amigoscode.realdb.check.probe; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUniqueId; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.ClassOrderer; +import org.junit.jupiter.api.ClassOrdererContext; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.MethodOrdererContext; +import org.junit.platform.engine.DiscoverySelector; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.engine.support.descriptor.ClassSource; +import org.junit.platform.engine.support.descriptor.MethodSource; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +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 YOUR test suite: every test class under src/test/java/com/amigoscode/realdb, except the + * checks themselves in check/. Each way of running it happens at most once per JVM and is remembered, + * so ./check runs the suite a handful of times, not once per check. + */ +public final class StudentSuite { + + /** The ways the checks run your suite. */ + public enum Variant { + AS_IS("as it is, classes and methods from A to Z"), + AGAIN("as it is, a second time in the same JVM"), + REVERSED("classes and methods from Z to A"), + SHIFTED_IDS("with every id sequence moved on by 1000 just before each test"), + TOP_RATED_BUG("with the start/ version of findTopRated put back"), + MISSING_MIGRATION_BUG("with V2__allow_audiobooks.sql taken out of the database"), + ON_CONFLICT_BUG("with the start/ version of subscribe put back"), + SHELF_ORDER_BUG("with the start/ version of findByShelf put back"); + + private final String description; + + Variant(String description) { + this.description = description; + } + + public String description() { + return description; + } + } + + /** The outcome of one of your tests. */ + public record TestResult(String uniqueId, String className, String methodName, String displayName, + boolean passed, String failure) { + + public String simpleClassName() { + return className.substring(className.lastIndexOf('.') + 1); + } + + public String name() { + return simpleClassName() + (methodName == null ? "" : "." + methodName); + } + } + + /** All your tests, as one run reported them. */ + public record Run(List tests, long millis) { + + public boolean allPassed() { + return !tests.isEmpty() && tests.stream().allMatch(TestResult::passed); + } + + public List failed() { + return tests.stream().filter(test -> !test.passed()).toList(); + } + + public Optional find(String name) { + return tests.stream().filter(test -> test.name().equals(name)).findFirst(); + } + + public long passedCount() { + return tests.stream().filter(TestResult::passed).count(); + } + } + + private static final String ROOT_PACKAGE = "com.amigoscode.realdb"; + private static final Map RUNS = new EnumMap<>(Variant.class); + private static Map alone; + private static volatile boolean running; + + private StudentSuite() { + } + + /** Your suite, run one way. The first call of all is always AS_IS, and that is the run the probe records. */ + public static synchronized Run run(Variant variant) { + if (!RUNS.containsKey(Variant.AS_IS)) { + Recording.start(); + try { + RUNS.put(Variant.AS_IS, execute(List.of(selectPackage(ROOT_PACKAGE)), false)); + } finally { + Recording.stop(); + } + } + if (!RUNS.containsKey(variant)) { + RUNS.put(variant, runVariant(variant)); + } + return RUNS.get(variant); + } + + /** + * Call just before System.exit. Closes the Spring contexts your tests left in Spring's cache, with + * the output switched off: otherwise they close in a shutdown hook, and Hibernate prints its + * DROP TABLE statements after the last line of the report. + */ + public static void shutDown() { + System.out.flush(); + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + Recording.closeAll(); + } + + static boolean isRunning() { + return running; + } + + /** Every test that passed in the AS_IS run, run again on its own, one at a time. */ + public static synchronized Map eachAlone() { + if (alone == null) { + alone = new LinkedHashMap<>(); + for (TestResult test : run(Variant.AS_IS).tests()) { + if (test.passed() && test.methodName() != null) { + Run single = execute(List.of(selectUniqueId(test.uniqueId())), false); + single.tests().stream().findFirst().ifPresent(result -> alone.put(test.name(), result)); + } + } + } + return Collections.unmodifiableMap(alone); + } + + private static Run runVariant(Variant variant) { + List everything = List.of(selectPackage(ROOT_PACKAGE)); + switch (variant) { + case AGAIN -> { + return execute(everything, false); + } + case REVERSED -> { + return execute(everything, true); + } + case SHIFTED_IDS -> { + SuiteProbe.shiftIds(true); + try { + return execute(everything, false); + } finally { + SuiteProbe.shiftIds(false); + } + } + default -> { + Mutant.activate(switch (variant) { + case TOP_RATED_BUG -> Mutant.TOP_RATED; + case MISSING_MIGRATION_BUG -> Mutant.MISSING_MIGRATION; + case ON_CONFLICT_BUG -> Mutant.ON_CONFLICT; + case SHELF_ORDER_BUG -> Mutant.SHELF_ORDER; + default -> throw new IllegalArgumentException(variant.name()); + }); + try { + return execute(everything, false); + } finally { + Mutant.deactivate(); + } + } + } + } + + private static Run execute(List selectors, boolean reversed) { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectors) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), + ClassNameFilter.excludeClassNamePatterns(SuiteProbe.CHECK_PACKAGE.replace(".", "\\.") + "\\..*")) + .configurationParameter("junit.jupiter.testclass.order.default", + reversed ? ZToAClasses.class.getName() : ClassOrderer.ClassName.class.getName()) + .configurationParameter("junit.jupiter.testmethod.order.default", + reversed ? ZToAMethods.class.getName() : MethodOrderer.MethodName.class.getName()) + .build(); + Collector collector = new Collector(); + long started = System.nanoTime(); + Launcher launcher = LauncherFactory.create(); + // Your tests may print (Hibernate's SQL, Spring's banner). The checks print their own summary. + PrintStream out = System.out; + PrintStream err = System.err; + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + running = true; + try { + launcher.execute(request, collector); + } finally { + running = false; + System.setOut(out); + System.setErr(err); + } + return new Run(List.copyOf(collector.results), (System.nanoTime() - started) / 1_000_000); + } + + private static final class Collector implements TestExecutionListener { + + private final List results = new ArrayList<>(); + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean passed = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + String failure = result.getThrowable().map(StudentSuite::reason).orElse(null); + if (test.isTest()) { + if (test.getSource().orElse(null) instanceof MethodSource method) { + results.add(new TestResult(test.getUniqueId(), method.getClassName(), method.getMethodName(), + test.getDisplayName(), passed, failure)); + } + } else if (!passed && test.getSource().orElse(null) instanceof ClassSource source) { + // The class itself failed, for example its container or its Spring context did not start. + results.add(new TestResult(test.getUniqueId(), source.getClassName(), null, + test.getDisplayName() + " could not start", false, failure)); + } + } + } + + /** For an assertion, its message. Otherwise the deepest cause with a message: usually the database's own words. */ + static String reason(Throwable throwable) { + String message = throwable.getMessage(); + if (!(throwable instanceof AssertionError)) { + for (Throwable cause = throwable; cause != null; cause = cause.getCause() == cause ? null : cause.getCause()) { + if (cause.getMessage() != null && !cause.getMessage().isBlank()) { + message = cause.getMessage(); + } + } + } + if (message == null) { + return throwable.getClass().getSimpleName(); + } + return String.join(" ", message.strip().lines().map(String::strip).filter(line -> !line.isEmpty()).limit(4).toList()); + } + + /** Classes from Z to A. */ + public static final class ZToAClasses implements ClassOrderer { + + @Override + public void orderClasses(ClassOrdererContext context) { + context.getClassDescriptors().sort((a, b) -> b.getTestClass().getName().compareTo(a.getTestClass().getName())); + } + } + + /** Methods from Z to A. A class with its own @TestMethodOrder keeps its own order. */ + public static final class ZToAMethods implements MethodOrderer { + + @Override + public void orderMethods(MethodOrdererContext context) { + context.getMethodDescriptors().sort((a, b) -> b.getMethod().getName().compareTo(a.getMethod().getName())); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java new file mode 100644 index 0000000..0b9419b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java @@ -0,0 +1,102 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.concurrent.atomic.AtomicLong; +import javax.sql.DataSource; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.JdbcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.TestExecutionListener; + +/** + * A Spring TestExecutionListener, registered in META-INF/spring.factories, so Spring runs it for every + * Spring test, yours included. It does nothing unless a check, ./demo or ./inspect is running your + * suite. Then it records which context each test class used and which database that context talks + * to, and it can put a bug back in ({@link Mutant}) or move the id sequences on. + */ +public class SuiteProbe implements TestExecutionListener, Ordered { + + static final String CHECK_PACKAGE = "com.amigoscode.realdb.check"; + + private static volatile boolean shiftIds; + private static final AtomicLong H2_RESTART = new AtomicLong(1_000_000); + + static boolean isYourTest(Class testClass) { + return !testClass.getName().startsWith(CHECK_PACKAGE + "."); + } + + static void shiftIds(boolean on) { + shiftIds = on; + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public void prepareTestInstance(TestContext testContext) { + Class testClass = testContext.getTestClass(); + if (!isYourTest(testClass) || !StudentSuite.isRunning()) { + return; + } + long started = System.nanoTime(); + ApplicationContext context = testContext.getApplicationContext(); + long loadMillis = (System.nanoTime() - started) / 1_000_000; + Recording.DatabaseInfo database; + if (Recording.isActive()) { + database = Recording.seen(testClass, kind(testClass), context, loadMillis).database; + } else { + database = Recording.describeOnce(context); + } + Mutant.prepareDatabase(context.getBeanProvider(DataSource.class).getIfUnique(), database); + } + + @Override + public void beforeTestExecution(TestContext testContext) { + if (!shiftIds || !isYourTest(testContext.getTestClass())) { + return; + } + DataSource dataSource = testContext.getApplicationContext().getBeanProvider(DataSource.class).getIfUnique(); + if (dataSource == null) { + return; + } + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + connection.setAutoCommit(true); + String product = connection.getMetaData().getDatabaseProductName(); + for (String table : new String[] {"book", "subscriber"}) { + try { + if (product.equalsIgnoreCase("PostgreSQL")) { + statement.execute("select setval(pg_get_serial_sequence('" + table + "', 'id'), " + + "nextval(pg_get_serial_sequence('" + table + "', 'id')) + 1000)"); + } else { + statement.execute("alter table " + table + " alter column id restart with " + H2_RESTART.addAndGet(1000)); + } + } catch (Exception e) { + // No such table in this context: nothing to move on. + } + } + } catch (Exception e) { + // The database is not reachable: the test will say so itself. + } + } + + static String kind(Class testClass) { + MergedAnnotations annotations = MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY); + if (annotations.isPresent(DataJpaTest.class)) { + return "@DataJpaTest"; + } + if (annotations.isPresent(JdbcTest.class)) { + return "@JdbcTest"; + } + if (annotations.isPresent(SpringBootTest.class)) { + return "@SpringBootTest"; + } + return "Spring test"; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java new file mode 100644 index 0000000..6c5bb03 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java @@ -0,0 +1,37 @@ +package com.amigoscode.realdb.check.support; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The checks' own Postgres, separate from the one your tests start. It is started once, the first + * time a check needs it, and Testcontainers removes it when the JVM ends. + */ +public final class CheckPostgres { + + private static PostgreSQLContainer container; + + private CheckPostgres() { + } + + public static synchronized PostgreSQLContainer container() { + if (container == null) { + container = new PostgreSQLContainer("postgres:17-alpine"); + container.start(); + } + return container; + } + + /** A plain JDBC connection to an empty database of its own, for the checks that compare H2 and Postgres. */ + public static Connection newDatabase(String name) throws SQLException { + PostgreSQLContainer postgres = container(); + try (Connection admin = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + admin.createStatement().execute("drop database if exists " + name); + admin.createStatement().execute("create database " + name); + } + String url = postgres.getJdbcUrl().replace("/" + postgres.getDatabaseName(), "/" + name); + return DriverManager.getConnection(url, postgres.getUsername(), postgres.getPassword()); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java new file mode 100644 index 0000000..93a2334 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.realdb.check.support; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.CatalogueService; +import com.amigoscode.realdb.subscription.SubscriptionService; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * Base class for the checks that ask "does the code in src/main work on real Postgres?". It runs the + * whole application, with the Flyway migrations, against the checks' own Postgres, the way production + * would. It does not look at your tests at all. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = "spring.main.banner-mode=off") +public abstract class ProductionTest { + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", () -> CheckPostgres.container().getJdbcUrl()); + registry.add("spring.datasource.username", () -> CheckPostgres.container().getUsername()); + registry.add("spring.datasource.password", () -> CheckPostgres.container().getPassword()); + } + + @Autowired + protected CatalogueService catalogue; + + @Autowired + protected SubscriptionService subscriptions; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyDatabase() { + jdbc.execute("truncate table book, subscriber restart identity"); + } + + protected static List titles(List books) { + return books.stream().map(Book::getTitle).toList(); + } + + /** Runs the action, and turns an exception into a failure that quotes the database's own words. */ + protected static T expectNoError(String what, java.util.function.Supplier action) { + try { + return action.get(); + } catch (RuntimeException e) { + Throwable deepest = e; + while (deepest.getCause() != null && deepest.getCause() != deepest) { + deepest = deepest.getCause(); + } + String message = String.valueOf(deepest.getMessage()); + throw new AssertionError(what + " failed on Postgres:\n" + message.lines().findFirst().orElse(message)); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java new file mode 100644 index 0000000..f67c2e7 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java @@ -0,0 +1,22 @@ +package com.amigoscode.realdb.check.support; + +import java.util.Map; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; + +/** + * Puts the checks' Postgres URL into the environment as an ordinary property source, the way + * application.properties would. (A @DynamicPropertySource URL is treated differently by @DataJpaTest.) + */ +public class UrlFromProperties implements ApplicationContextInitializer { + + @Override + public void initialize(ConfigurableApplicationContext context) { + var postgres = CheckPostgres.container(); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("like-application-properties", Map.of( + "spring.datasource.url", postgres.getJdbcUrl(), + "spring.datasource.username", postgres.getUsername(), + "spring.datasource.password", postgres.getPassword()))); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java new file mode 100644 index 0000000..e93d5f2 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java @@ -0,0 +1,84 @@ +package com.amigoscode.realdb.check.support; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** The questions the checks ask about YOUR test suite, with failure messages that say what to do. */ +public final class YourSuite { + + private YourSuite() { + } + + /** + * Passes if at least one test that is green on the current code turns red with the bug put back. + * That is what "your tests catch the bug" means. A test only counts if it is also green when the + * suite runs a second time without the bug: then the bug, and nothing else, turned it red. + */ + public static void catches(Variant bug, String hint) { + Run asIs = StudentSuite.run(Variant.AS_IS); + Run again = StudentSuite.run(Variant.AGAIN); + Run withBug = StudentSuite.run(bug); + List caughtBy = new ArrayList<>(); + List unstable = new ArrayList<>(); + for (TestResult test : asIs.tests()) { + boolean greenAgain = again.find(test.name()).map(TestResult::passed).orElse(false); + if (test.passed() && !greenAgain) { + unstable.add(test.name() + ": " + again.find(test.name()).map(TestResult::failure).orElse("did not run")); + } else if (test.passed() && withBug.find(test.name()).map(result -> !result.passed()).orElse(false)) { + caughtBy.add(test.name()); + } + } + if (caughtBy.isEmpty()) { + fail("Your suite ran " + bug.description() + ", and no test that passes now failed." + + "\nSo it would not catch this bug. " + hint + + (unstable.isEmpty() ? "" : "\nThese tests do not count: they fail when the suite runs a second time," + + " even without the bug:\n" + String.join("\n", unstable))); + } + } + + /** Which database each of your Spring test classes talked to, as "Class: database". */ + public static String databases() { + Map, Recording.ContextInfo> classes = Recording.classes(); + if (classes.isEmpty()) { + return "(none of your test classes started Spring)"; + } + return classes.entrySet().stream() + .map(entry -> entry.getKey().getSimpleName() + ": " + entry.getValue().database.describe()) + .collect(Collectors.joining("\n")); + } + + public static Recording.DatabaseInfo databaseOf(String simpleClassName) { + StudentSuite.run(Variant.AS_IS); + return Recording.classes().entrySet().stream() + .filter(entry -> entry.getKey().getSimpleName().equals(simpleClassName)) + .map(entry -> entry.getValue().database) + .findFirst() + .orElseGet(() -> fail(simpleClassName + " did not start a Spring context, or does not exist." + + "\nIt should be a @DataJpaTest in src/test/java/com/amigoscode/realdb/.")); + } + + /** Tests that passed in the normal run and failed in the other one. */ + public static List brokenBy(Map other) { + List broken = new ArrayList<>(); + for (TestResult test : StudentSuite.run(Variant.AS_IS).tests()) { + TestResult result = other.get(test.name()); + if (test.passed() && result != null && !result.passed()) { + broken.add(test.name() + ": " + result.failure()); + } + } + return broken; + } + + public static Map byName(Run run) { + return run.tests().stream().collect(Collectors.toMap(TestResult::name, test -> test, (a, b) -> a)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java new file mode 100644 index 0000000..b9247c0 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java @@ -0,0 +1,24 @@ +package com.amigoscode.realdb.subscription; + +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +/** + * An in-memory stand-in for SubscriberRepository. It does what we BELIEVE the SQL does. It cannot + * tell us whether the SQL really does it: that is SubscriberRepositoryTest's job, on Postgres. + */ +class FakeSubscriberRepository implements SubscriberRepository { + + private final Set addresses = new HashSet<>(); + + @Override + public int subscribe(String email) { + return addresses.add(email.toLowerCase(Locale.ROOT)) ? 1 : 0; + } + + @Override + public long count() { + return addresses.size(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java new file mode 100644 index 0000000..37b3648 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriberRepositoryTest.java @@ -0,0 +1,30 @@ +package com.amigoscode.realdb.subscription; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.support.PostgresTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; + +/** The SQL that the fake in SubscriptionServiceTest only pretends to run, on real Postgres. */ +@DataJpaTest +class SubscriberRepositoryTest extends PostgresTest { + + @Autowired + SubscriberRepository subscribers; + + @Test + void subscribesANewAddress() { + assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1); + assertThat(subscribers.count()).isEqualTo(1); + } + + @Test + void theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce() { + assertThat(subscribers.subscribe("ann@example.com")).isEqualTo(1); + assertThat(subscribers.subscribe("Ann@Example.COM")).isEqualTo(0); + + assertThat(subscribers.count()).isEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java new file mode 100644 index 0000000..1bbc06e --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java @@ -0,0 +1,38 @@ +package com.amigoscode.realdb.subscription; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.realdb.subscription.SubscriptionService.Outcome; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for the service's own logic, with a fake repository: no Spring, no database, a few + * milliseconds. They say nothing about the SQL in SubscriberRepository. + */ +class SubscriptionServiceTest { + + private final FakeSubscriberRepository subscribers = new FakeSubscriberRepository(); + private final SubscriptionService service = new SubscriptionService(subscribers); + + @Test + void aNewAddressIsSubscribed() { + assertThat(service.subscribe("ann@example.com")).isEqualTo(Outcome.SUBSCRIBED); + } + + @Test + void whenTheRepositoryAddsNothingTheAddressWasAlreadySubscribed() { + service.subscribe("ann@example.com"); + + assertThat(service.subscribe("Ann@Example.com")).isEqualTo(Outcome.ALREADY_SUBSCRIBED); + assertThat(subscribers.count()).isEqualTo(1); + } + + @Test + void rejectsSomethingThatIsNotAnEmailAddress() { + assertThatThrownBy(() -> service.subscribe("ann at example dot com")) + .isInstanceOf(InvalidEmailException.class); + + assertThat(subscribers.count()).isZero(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/support/PostgresTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/support/PostgresTest.java new file mode 100644 index 0000000..5d68ce6 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/java/com/amigoscode/realdb/support/PostgresTest.java @@ -0,0 +1,47 @@ +package com.amigoscode.realdb.support; + +import javax.sql.DataSource; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.jdbc.core.JdbcTemplate; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * One real Postgres for the whole test run. Every test class that needs a database extends this + * class, whatever kind of test it is (@DataJpaTest, @SpringBootTest). + * + *

    + *
  • The container is a static field, started once in a static block. It is not a JUnit + * {@code @Container}, so it is not stopped after each test class: it lives until the JVM ends, + * and Testcontainers removes it then.
  • + *
  • {@code @ServiceConnection} tells Spring Boot to take the URL, user and password from it. It + * also stops {@code @DataJpaTest} from swapping it for an embedded database.
  • + *
  • Every subclass declares the same container in the same place, so Spring's context cache can + * give all @DataJpaTest classes one context, and all @SpringBootTest classes another.
  • + *
  • The schema comes from the Flyway migrations in src/main/resources/db/migration, exactly as + * in production.
  • + *
+ */ +public abstract class PostgresTest { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine"); + + static { + POSTGRES.start(); + } + + @Autowired + private DataSource dataSource; + + /** + * Every test starts from empty tables, whatever ran before it. A rollback only cleans up after the + * test it belongs to: it cannot remove what an HTTP test committed. Ids keep counting up, on purpose: + * no test may depend on their values. Inside a @DataJpaTest the TRUNCATE is rolled back with the rest. + */ + @BeforeEach + void startFromEmptyTables() { + new JdbcTemplate(dataSource).execute("truncate table book, subscriber"); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/META-INF/spring.factories b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/META-INF/spring.factories new file mode 100644 index 0000000..3f7b152 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +# Part of the acceptance checks (src/test/java/com/amigoscode/realdb/check). Do not edit. +# Both do nothing during a normal test run. See check/probe/SuiteProbe.java. +org.springframework.test.context.TestExecutionListener=\ +com.amigoscode.realdb.check.probe.SuiteProbe +org.springframework.test.context.ContextCustomizerFactory=\ +com.amigoscode.realdb.check.probe.MutantContextCustomizerFactory diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..1785fb1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/solution/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + + + + diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/.mvn/jvm.config b/java/concepts/junior-mid/17-testing-with-a-real-database/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/start/check b/java/concepts/junior-mid/17-testing-with-a-real-database/start/check new file mode 100755 index 0000000..790e98e --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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.realdb.check.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/check.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/start/check.cmd new file mode 100644 index 0000000..eed036c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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.realdb.check.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/compose.yaml b/java/concepts/junior-mid/17-testing-with-a-real-database/start/compose.yaml new file mode 100644 index 0000000..2d3ffc3 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/compose.yaml @@ -0,0 +1,16 @@ +name: testing-with-a-real-database +services: + postgres: + image: postgres:17-alpine + container_name: testing-with-a-real-database-postgres + environment: + POSTGRES_DB: shop + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + ports: + - "5456:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U shop -d shop"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/demo b/java/concepts/junior-mid/17-testing-with-a-real-database/start/demo new file mode 100755 index 0000000..402789c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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 test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Demo -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/demo.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/start/demo.cmd new file mode 100644 index 0000000..1b65591 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Demo" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect b/java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect new file mode 100755 index 0000000..10bb2f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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 test-compile exec:java -Dexec.mainClass=com.amigoscode.realdb.check.Inspect -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/start/inspect.cmd new file mode 100644 index 0000000..99f2d61 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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" test-compile exec:java "-Dexec.mainClass=com.amigoscode.realdb.check.Inspect" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/mvnw b/java/concepts/junior-mid/17-testing-with-a-real-database/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/start/mvnw.cmd b/java/concepts/junior-mid/17-testing-with-a-real-database/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/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/17-testing-with-a-real-database/start/pom.xml b/java/concepts/junior-mid/17-testing-with-a-real-database/start/pom.xml new file mode 100644 index 0000000..0b7e35b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + testing-with-a-real-database + 0.0.1-SNAPSHOT + testing-with-a-real-database + Testing data access against a real Postgres with Testcontainers instead of H2 or mocks + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-flyway + + + org.flywaydb + flyway-database-postgresql + + + 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.springframework.boot + spring-boot-testcontainers + test + + + org.testcontainers + testcontainers-postgresql + test + + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + com.h2database + h2 + 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/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java new file mode 100644 index 0000000..5a8f484 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/ApiExceptionHandler.java @@ -0,0 +1,23 @@ +package com.amigoscode.realdb; + +import com.amigoscode.realdb.catalogue.BookNotFoundException; +import com.amigoscode.realdb.subscription.InvalidEmailException; +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class ApiExceptionHandler { + + @ExceptionHandler(BookNotFoundException.class) + ResponseEntity> notFound(BookNotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("code", "BOOK_NOT_FOUND", "message", e.getMessage())); + } + + @ExceptionHandler(InvalidEmailException.class) + ResponseEntity> invalidEmail(InvalidEmailException e) { + return ResponseEntity.badRequest().body(Map.of("code", "INVALID_EMAIL", "message", e.getMessage())); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java new file mode 100644 index 0000000..f16f735 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/RealDatabaseApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.realdb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RealDatabaseApplication { + + public static void main(String[] args) { + SpringApplication.run(RealDatabaseApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Book.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Book.java new file mode 100644 index 0000000..da07ac2 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Book.java @@ -0,0 +1,81 @@ +package com.amigoscode.realdb.catalogue; + +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.math.BigDecimal; +import java.time.Instant; + +@Entity +@Table(name = "book") +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String title; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private Format format; + + /** Average review score from 1.0 to 5.0. Null until the book has its first review. */ + @Column(precision = 2, scale = 1) + private BigDecimal rating; + + @Column(nullable = false) + private String shelf; + + @Column(name = "added_at", nullable = false) + private Instant addedAt; + + protected Book() { + } + + public Book(String title, Format format, String shelf) { + this.title = title; + this.format = format; + this.shelf = shelf; + this.addedAt = Instant.now(); + } + + public void rate(BigDecimal rating) { + this.rating = rating; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public Format getFormat() { + return format; + } + + public BigDecimal getRating() { + return rating; + } + + public String getShelf() { + return shelf; + } + + public Instant getAddedAt() { + return addedAt; + } + + @Override + public String toString() { + return title; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java new file mode 100644 index 0000000..028d096 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookNotFoundException.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.catalogue; + +public class BookNotFoundException extends RuntimeException { + + public BookNotFoundException(long id) { + super("No book with id " + id); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java new file mode 100644 index 0000000..74a67e9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/BookRepository.java @@ -0,0 +1,17 @@ +package com.amigoscode.realdb.catalogue; + +import java.util.List; +import org.springframework.data.domain.Limit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +/** The acceptance checks call findTopRated and findByShelf by name: fix them, do not rename them. */ +public interface BookRepository extends JpaRepository { + + /** The best rated books first. A book without a rating has no reviews yet: it goes last. */ + @Query("select b from Book b order by b.rating desc") + List findTopRated(Limit limit); + + /** The books on one shelf, in the order they were added. */ + List findByShelf(String shelf); +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java new file mode 100644 index 0000000..ea4458d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueController.java @@ -0,0 +1,58 @@ +package com.amigoscode.realdb.catalogue; + +import java.math.BigDecimal; +import java.net.URI; +import java.util.List; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +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.RestController; + +@RestController +@RequestMapping("/api") +public class CatalogueController { + + public record NewBook(String title, Format format, String shelf) { + } + + public record NewRating(BigDecimal rating) { + } + + public record BookView(long id, String title, Format format, BigDecimal rating, String shelf) { + + static BookView of(Book book) { + return new BookView(book.getId(), book.getTitle(), book.getFormat(), book.getRating(), book.getShelf()); + } + } + + private final CatalogueService catalogue; + + public CatalogueController(CatalogueService catalogue) { + this.catalogue = catalogue; + } + + @PostMapping("/books") + public ResponseEntity addBook(@RequestBody NewBook request) { + Book book = catalogue.addBook(request.title(), request.format(), request.shelf()); + return ResponseEntity.created(URI.create("/api/books/" + book.getId())).body(BookView.of(book)); + } + + @PutMapping("/books/{id}/rating") + public BookView rate(@PathVariable long id, @RequestBody NewRating request) { + return BookView.of(catalogue.rate(id, request.rating())); + } + + @GetMapping("/books/top-rated") + public List topRated() { + return catalogue.topRated().stream().map(BookView::of).toList(); + } + + @GetMapping("/shelves/{shelf}") + public List shelf(@PathVariable String shelf) { + return catalogue.shelf(shelf).stream().map(BookView::of).toList(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java new file mode 100644 index 0000000..aa0e899 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/CatalogueService.java @@ -0,0 +1,41 @@ +package com.amigoscode.realdb.catalogue; + +import java.math.BigDecimal; +import java.util.List; +import org.springframework.data.domain.Limit; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class CatalogueService { + + static final int TOP_RATED_SIZE = 3; + + private final BookRepository books; + + public CatalogueService(BookRepository books) { + this.books = books; + } + + @Transactional + public Book addBook(String title, Format format, String shelf) { + return books.save(new Book(title, format, shelf)); + } + + @Transactional + public Book rate(long bookId, BigDecimal rating) { + Book book = books.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId)); + book.rate(rating); + return book; + } + + @Transactional(readOnly = true) + public List topRated() { + return books.findTopRated(Limit.of(TOP_RATED_SIZE)); + } + + @Transactional(readOnly = true) + public List shelf(String shelf) { + return books.findByShelf(shelf); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Format.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Format.java new file mode 100644 index 0000000..df65f14 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/catalogue/Format.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.catalogue; + +public enum Format { + PAPERBACK, + HARDCOVER, + EBOOK, + AUDIOBOOK +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java new file mode 100644 index 0000000..5d8a0a7 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/InvalidEmailException.java @@ -0,0 +1,8 @@ +package com.amigoscode.realdb.subscription; + +public class InvalidEmailException extends RuntimeException { + + public InvalidEmailException(String email) { + super("Not an email address: " + email); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java new file mode 100644 index 0000000..5f73e69 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/Subscriber.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.subscription; + +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 = "subscriber") +public class Subscriber { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String email; + + @Column(name = "subscribed_at", nullable = false, insertable = false, updatable = false) + private Instant subscribedAt; + + protected Subscriber() { + } + + public Long getId() { + return id; + } + + public String getEmail() { + return email; + } + + public Instant getSubscribedAt() { + return subscribedAt; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java new file mode 100644 index 0000000..23d474f --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriberRepository.java @@ -0,0 +1,27 @@ +package com.amigoscode.realdb.subscription; + +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +/** The acceptance checks call subscribe by name: fix it, do not rename it. */ +public interface SubscriberRepository extends Repository { + + /** + * Adds the address unless it is already subscribed, in any capitalisation. One statement, so two + * requests for the same address at the same moment cannot both insert it. + * + * @return 1 if the address was added, 0 if it was already there + */ + @Modifying + @Transactional + @Query(value = """ + insert into subscriber (email) values (:email) + on conflict (email) do nothing + """, nativeQuery = true) + int subscribe(@Param("email") String email); + + long count(); +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java new file mode 100644 index 0000000..fe55578 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionController.java @@ -0,0 +1,29 @@ +package com.amigoscode.realdb.subscription; + +import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SubscriptionController { + + public record NewSubscriber(String email) { + } + + private final SubscriptionService subscriptions; + + public SubscriptionController(SubscriptionService subscriptions) { + this.subscriptions = subscriptions; + } + + /** 201 for a new subscriber, 200 if the address was already subscribed. */ + @PostMapping("/api/subscribers") + public ResponseEntity> subscribe(@RequestBody NewSubscriber request) { + SubscriptionService.Outcome outcome = subscriptions.subscribe(request.email()); + HttpStatus status = outcome == SubscriptionService.Outcome.SUBSCRIBED ? HttpStatus.CREATED : HttpStatus.OK; + return ResponseEntity.status(status).body(Map.of("outcome", outcome.name())); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java new file mode 100644 index 0000000..44c176d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/java/com/amigoscode/realdb/subscription/SubscriptionService.java @@ -0,0 +1,27 @@ +package com.amigoscode.realdb.subscription; + +import java.util.regex.Pattern; +import org.springframework.stereotype.Service; + +@Service +public class SubscriptionService { + + public enum Outcome { SUBSCRIBED, ALREADY_SUBSCRIBED } + + private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+\\.[^@\\s]+"); + + private final SubscriberRepository subscribers; + + public SubscriptionService(SubscriberRepository subscribers) { + this.subscribers = subscribers; + } + + /** Subscribes an address to the newsletter. Subscribing twice is fine: the second time changes nothing. */ + public Outcome subscribe(String email) { + String address = email == null ? "" : email.strip(); + if (!EMAIL.matcher(address).matches()) { + throw new InvalidEmailException(email); + } + return subscribers.subscribe(address) == 1 ? Outcome.SUBSCRIBED : Outcome.ALREADY_SUBSCRIBED; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/application.properties b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/application.properties new file mode 100644 index 0000000..7ba0fda --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/application.properties @@ -0,0 +1,13 @@ +spring.application.name=testing-with-a-real-database + +# Postgres from compose.yaml. Port 5456 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5456/shop} +spring.datasource.username=${DB_USER:shop} +spring.datasource.password=${DB_PASSWORD:shop} + +# The schema comes from Flyway (src/main/resources/db/migration), never from Hibernate. +spring.jpa.hibernate.ddl-auto=none +spring.jpa.open-in-view=false + +# Uncomment to see every SQL statement. +# logging.level.org.hibernate.SQL=DEBUG diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/db/migration/V1__create_catalogue.sql b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/db/migration/V1__create_catalogue.sql new file mode 100644 index 0000000..d2d099d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/main/resources/db/migration/V1__create_catalogue.sql @@ -0,0 +1,20 @@ +create table book ( + id bigint generated by default as identity primary key, + title text not null, + format varchar(20) not null, + rating numeric(2, 1), -- null until the book has its first review + shelf text not null, + added_at timestamptz not null default now(), + constraint book_format_check check (format in ('PAPERBACK', 'HARDCOVER', 'EBOOK')), + constraint book_rating_check check (rating between 1.0 and 5.0) +); + +create table subscriber ( + id bigint generated by default as identity primary key, + email text not null, + subscribed_at timestamptz not null default now() +); + +-- One subscription per address, whatever the capitalisation: +-- Ann@Example.com and ann@example.com are the same person. +create unique index subscriber_email_key on subscriber (lower(email)); diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java new file mode 100644 index 0000000..12deb24 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/BookRepositoryTest.java @@ -0,0 +1,48 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.data.domain.Limit; + +/** + * The repository against a quick in-memory database. Flyway is off because the migrations do not + * run on H2: Hibernate creates the tables from the entities instead. + */ +@DataJpaTest(properties = { + "spring.flyway.enabled=false", + "spring.jpa.hibernate.ddl-auto=create-drop"}) +class BookRepositoryTest { + + @Autowired + BookRepository books; + + @Test + void topRatedComesBestFirstAndUnratedBooksLast() { + rated("Dune", "4.8"); + rated("Emma", "3.9"); + books.save(new Book("No Reviews Yet", Format.PAPERBACK, "fiction")); + rated("Hamlet", "4.2"); + + assertThat(books.findTopRated(Limit.of(3))) + .extracting(Book::getTitle) + .containsExactly("Dune", "Hamlet", "Emma"); + } + + @Test + void savesAnAudiobook() { + Book saved = books.saveAndFlush(new Book("Dune", Format.AUDIOBOOK, "fiction")); + + assertThat(books.findById(saved.getId())).get() + .extracting(Book::getFormat) + .isEqualTo(Format.AUDIOBOOK); + } + + private void rated(String title, String rating) { + Book book = books.save(new Book(title, Format.PAPERBACK, "fiction")); + book.rate(new BigDecimal(rating)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java new file mode 100644 index 0000000..369381f --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/CatalogueApiTest.java @@ -0,0 +1,68 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.catalogue.CatalogueController.BookView; +import com.amigoscode.realdb.catalogue.CatalogueController.NewBook; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestClient; + +/** The whole application over HTTP, on H2 in PostgreSQL mode. */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { + "spring.datasource.url=jdbc:h2:mem:catalogue;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE", + "spring.flyway.enabled=false", + "spring.jpa.hibernate.ddl-auto=create-drop"}) +@Transactional // every test is rolled back +@DirtiesContext // a fresh database for the next test class +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CatalogueApiTest { + + @LocalServerPort + int port; + + RestClient http; + + @BeforeEach + void client() { + http = RestClient.create("http://localhost:" + port); + } + + @Test + @Order(1) + void addsABook() { + ResponseEntity response = add("Beloved", "fiction"); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(response.getBody().id()).isEqualTo(1); + assertThat(response.getHeaders().getLocation()).hasToString("/api/books/1"); + } + + @Test + @Order(2) + void listsTheShelf() { + // Beloved was added by addsABook + List shelf = http.get().uri("/api/shelves/fiction").retrieve() + .body(new ParameterizedTypeReference<>() { }); + + assertThat(shelf).extracting(BookView::title).containsExactly("Beloved"); + } + + private ResponseEntity add(String title, String shelf) { + return http.post().uri("/api/books") + .body(new NewBook(title, Format.PAPERBACK, shelf)) + .retrieve() + .toEntity(BookView.class); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java new file mode 100644 index 0000000..c664ff4 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/catalogue/ShelfTest.java @@ -0,0 +1,29 @@ +package com.amigoscode.realdb.catalogue; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; + +@DataJpaTest(properties = { + "spring.flyway.enabled=false", + "spring.jpa.hibernate.ddl-auto=create-drop", + "spring.jpa.properties.hibernate.format_sql=true"}) // left over from debugging a query +class ShelfTest { + + @Autowired + BookRepository books; + + @Test + void shelfListsBooksInTheOrderTheyWereAdded() { + books.save(new Book("Beloved", Format.PAPERBACK, "fiction")); + books.save(new Book("Middlemarch", Format.HARDCOVER, "fiction")); + books.save(new Book("Rebecca", Format.EBOOK, "fiction")); + books.save(new Book("Ariel", Format.PAPERBACK, "poetry")); + + assertThat(books.findByShelf("fiction")) + .extracting(Book::getTitle) + .containsExactly("Beloved", "Middlemarch", "Rebecca"); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Check.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Check.java new file mode 100644 index 0000000..8969583 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Check.java @@ -0,0 +1,131 @@ +package com.amigoscode.realdb.check; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import java.io.OutputStream; +import java.io.PrintStream; +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 acceptance checks that belong to one task and prints one line per criterion. + * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2 + * (./mvnw verify runs the same checks the usual Maven way.) + * + *

Two kinds of check live in this package. "Production: ..." runs the code in src/main against the + * checks' own Postgres. "Your suite: ..." runs YOUR tests (everything under src/test/java outside this + * package) through the JUnit launcher, sometimes with a bug put back in, and looks at what they did. + */ +public final class Check { + + /** Tasks that have checks. Task 8 is an inspection task with nothing to run: you answer questions. */ + private static final Map TASKS = new LinkedHashMap<>(); + + static { + TASKS.put("baseline", "Baseline: your test suite is green (passes from the start, must end green)"); + TASKS.put("1", "Task 1: See it break: H2 and Postgres disagree"); + TASKS.put("2", "Task 2: Run the repository tests on Postgres, fix what they find"); + TASKS.put("3", "Task 3: Inspect what @DataJpaTest does with your database"); + TASKS.put("4", "Task 4: Replace the fake where it hides the SQL"); + TASKS.put("5", "Task 5: One container, one context per kind of test"); + TASKS.put("6", "Task 6: Tests that own their data"); + TASKS.put("7", "Task 7: Order you can rely on"); + } + + /** The terminal. While the checks run, System.out goes nowhere: Spring and Hibernate print too much. */ + private static final PrintStream OUT = System.out; + + public static void main(String[] args) { + if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) { + 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])) { + OUT.println(); + OUT.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:"); + OUT.println("follow its steps in INTERVIEW_TASKS.md and answer the questions."); + OUT.println(); + return; + } + + boolean allGreen = true; + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + 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(); + OUT.println(); + OUT.println(task.getValue()); + Results results = new Results(); + launcher.execute(request, results); + OUT.println(" " + results.passed + " of " + results.total + " pass"); + allGreen &= results.passed == results.total && results.total > 0; + } + OUT.println(); + OUT.flush(); + StudentSuite.shutDown(); + 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++; + OUT.println(" [FAIL] " + test.getDisplayName() + " could not start"); + result.getThrowable().ifPresent(Results::printReason); + } + return; + } + total++; + if (ok) { + passed++; + OUT.println(" [PASS] " + test.getDisplayName()); + } else { + 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 -> OUT.println(" " + line)); + } + } + + private Check() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java new file mode 100644 index 0000000..a170cab --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestKeepsAServiceConnectionIT.java @@ -0,0 +1,35 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.CheckPostgres; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** Task 3. Passes from the start: Spring Boot 4 does not replace a @ServiceConnection container. */ +@Tag("task3") +@DataJpaTest(properties = "spring.main.banner-mode=off") +class DataJpaTestKeepsAServiceConnectionIT { + + @ServiceConnection + static final PostgreSQLContainer POSTGRES = CheckPostgres.container(); + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: a @ServiceConnection container is kept, with no extra annotation: the test runs on Postgres") + void keptPostgres() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java new file mode 100644 index 0000000..05aaefd --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestReplacesYourDatabaseIT.java @@ -0,0 +1,38 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.UrlFromProperties; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; + +/** + * Task 3. Passes from the start: it documents what Spring Boot 4 does. The URL points at a real + * Postgres, but it comes from an ordinary property source, and H2 is on the classpath, so + * @DataJpaTest swaps the DataSource for an embedded H2. (Flyway is off because the real migrations + * cannot run on H2.) + */ +@Tag("task3") +@DataJpaTest(showSql = false, properties = {"spring.flyway.enabled=false", "spring.main.banner-mode=off"}) +@ContextConfiguration(initializers = UrlFromProperties.class) +class DataJpaTestReplacesYourDatabaseIT { + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: a datasource URL from application.properties is swapped for an embedded H2") + void swappedForH2() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("H2"); + assertThat(connection.getMetaData().getURL()).startsWith("jdbc:h2:mem:"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java new file mode 100644 index 0000000..288a9dd --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/DataJpaTestWithReplaceNoneIT.java @@ -0,0 +1,34 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.check.support.UrlFromProperties; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +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.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; +import org.springframework.test.context.ContextConfiguration; + +/** Task 3. Passes from the start: the same URL as DataJpaTestReplacesYourDatabaseIT, kept this time. */ +@Tag("task3") +@DataJpaTest(properties = "spring.main.banner-mode=off") +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@ContextConfiguration(initializers = UrlFromProperties.class) +class DataJpaTestWithReplaceNoneIT { + + @Autowired + DataSource dataSource; + + @Test + @DisplayName("@DataJpaTest: with @AutoConfigureTestDatabase(replace = NONE) the same URL is kept: the test runs on Postgres") + void keptPostgres() throws SQLException { + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Db.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Db.java new file mode 100644 index 0000000..2a0722b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Db.java @@ -0,0 +1,47 @@ +package com.amigoscode.realdb.check; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +/** The "production" Postgres from compose.yaml. Same defaults as application.properties. */ +final class Db { + + static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5456/shop"); + static final String USER = env("DB_USER", "shop"); + static final String PASSWORD = env("DB_PASSWORD", "shop"); + + private Db() { + } + + /** Returns false, after printing what to do, when Postgres is not reachable. */ + static boolean isUp() { + try (Connection ignored = DriverManager.getConnection(URL, USER, PASSWORD)) { + 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; + } + } + + /** Drops every table, so the application's Flyway migrations build the schema from scratch. */ + static void empty() throws SQLException { + try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); + Statement statement = connection.createStatement()) { + statement.execute("drop schema public cascade"); + statement.execute("create schema public"); + } + } + + 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/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Demo.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Demo.java new file mode 100644 index 0000000..f3ec54c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Demo.java @@ -0,0 +1,202 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.RealDatabaseApplication; +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.CatalogueService; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.subscription.SubscriptionService; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs your test suite, then the same four features in "production": the code in src/main, on the + * Postgres from compose.yaml, with the schema built by the Flyway migrations. Run it with ./demo + * (or .\demo on Windows). + */ +public final class Demo { + + /** One feature, tried in production. */ + private record Scenario(String name, boolean ok, List lines) { + } + + public static void main(String[] args) throws Exception { + show(args); + // The Spring contexts of your tests are still cached, with their threads: end the JVM here. + StudentSuite.shutDown(); + System.exit(0); + } + + private static void show(String[] args) throws Exception { + if (args.length > 0) { + System.out.println("Usage: ./demo (Windows: .\\demo)"); + System.out.println(); + System.out.println("Runs your test suite, then the same features on real Postgres (docker compose up -d first)."); + return; + } + if (!Db.isUp()) { + return; + } + + System.out.println(); + System.out.println("1. YOUR TEST SUITE (src/test/java, everything outside check/)"); + System.out.println(); + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + Report.tests(run, "[GREEN]", "[RED] "); + System.out.println(); + System.out.println(" " + run.tests().size() + " tests: " + run.passedCount() + " green, " + + run.failed().size() + " red, in " + run.millis() + " ms. The database each test class used:"); + System.out.println(); + Report.databases(run); + + Db.empty(); + SpringApplication app = new SpringApplication(RealDatabaseApplication.class); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + List scenarios = new ArrayList<>(); + String migrations; + String version; + try (ConfigurableApplicationContext context = app.run("--spring.main.web-application-type=none")) { + JdbcTemplate jdbc = context.getBean(JdbcTemplate.class); + CatalogueService catalogue = context.getBean(CatalogueService.class); + SubscriptionService subscriptions = context.getBean(SubscriptionService.class); + version = jdbc.queryForObject("show server_version", String.class).split(" ")[0]; + migrations = jdbc.queryForList("select 'V' || version || ' ' || description from flyway_schema_history" + + " where success order by installed_rank", String.class).stream().collect(Collectors.joining(", ")); + scenarios.add(topRated(catalogue)); + scenarios.add(audiobook(catalogue)); + scenarios.add(subscribeTwice(subscriptions, jdbc)); + scenarios.add(shelf(catalogue)); + } + + System.out.println(); + System.out.println("2. PRODUCTION: the same features, the code in src/main, on PostgreSQL " + version); + System.out.println(" (compose.yaml, " + Db.URL + "), schema from Flyway: " + migrations); + System.out.println(); + for (Scenario scenario : scenarios) { + System.out.println(" " + (scenario.ok() ? "[OK] " : "[BROKEN]") + " " + scenario.name()); + for (String line : scenario.lines()) { + System.out.println(" " + line); + } + } + + long broken = scenarios.stream().filter(scenario -> !scenario.ok()).count(); + System.out.println(); + if (run.allPassed() && broken > 0) { + System.out.println("RESULT: YOUR TESTS SAY GREEN, PRODUCTION SAYS BROKEN. " + run.passedCount() + " of " + + run.tests().size() + " tests pass, and " + broken + " of " + scenarios.size() + + " features are broken on Postgres."); + } else if (broken > 0) { + System.out.println("RESULT: BROKEN, AND YOUR TESTS SEE IT. " + run.failed().size() + " of " + run.tests().size() + + " tests fail, and " + broken + " of " + scenarios.size() + " features are broken on Postgres."); + } else if (!run.allPassed()) { + System.out.println("RESULT: PRODUCTION WORKS, BUT " + run.failed().size() + " OF " + run.tests().size() + + " TESTS FAIL. A red test on working code is a test to fix."); + } else { + System.out.println("RESULT: OK. All " + run.tests().size() + " tests pass, and all " + scenarios.size() + + " features work on Postgres."); + } + System.out.println(); + } + + private static Scenario topRated(CatalogueService catalogue) { + try { + rated(catalogue, "Dune", "4.8"); + rated(catalogue, "Emma", "3.9"); + catalogue.addBook("No Reviews Yet", Format.PAPERBACK, "fiction"); + rated(catalogue, "Hamlet", "4.2"); + List top = catalogue.topRated(); + boolean ok = true; + boolean unratedSeen = false; + for (Book book : top) { + unratedSeen |= book.getRating() == null; + ok &= book.getRating() == null || !unratedSeen; + } + List lines = new ArrayList<>(); + lines.add("added: Dune 4.8, Emma 3.9, No Reviews Yet (no rating), Hamlet 4.2"); + lines.add("top 3: " + describe(top)); + if (!ok) { + lines.add("A book nobody has reviewed is ahead of the best rated ones."); + } + return new Scenario("Top rated", ok, lines); + } catch (RuntimeException e) { + return new Scenario("Top rated", false, List.of(error(e))); + } + } + + private static Scenario audiobook(CatalogueService catalogue) { + try { + Book book = catalogue.addBook("Dune", Format.AUDIOBOOK, "audio"); + return new Scenario("Add an audiobook", true, List.of("saved: " + book.getTitle() + " (" + book.getFormat() + "), id " + book.getId())); + } catch (RuntimeException e) { + return new Scenario("Add an audiobook", false, List.of(error(e))); + } + } + + private static Scenario subscribeTwice(SubscriptionService subscriptions, JdbcTemplate jdbc) { + String name = "Subscribe ann@example.com, then Ann@Example.COM"; + try { + SubscriptionService.Outcome first = subscriptions.subscribe("ann@example.com"); + SubscriptionService.Outcome second = subscriptions.subscribe("Ann@Example.COM"); + int rows = jdbc.queryForObject("select count(*) from subscriber", Integer.class); + boolean ok = first == SubscriptionService.Outcome.SUBSCRIBED + && second == SubscriptionService.Outcome.ALREADY_SUBSCRIBED && rows == 1; + return new Scenario(name, ok, List.of(first + ", then " + second + ". Rows in subscriber: " + rows)); + } catch (RuntimeException e) { + return new Scenario(name, false, List.of(error(e))); + } + } + + private static Scenario shelf(CatalogueService catalogue) { + String name = "Shelf \"classics\" after a review of Beloved"; + try { + Book beloved = catalogue.addBook("Beloved", Format.PAPERBACK, "classics"); + catalogue.addBook("Middlemarch", Format.HARDCOVER, "classics"); + catalogue.addBook("Rebecca", Format.EBOOK, "classics"); + catalogue.rate(beloved.getId(), new BigDecimal("4.5")); + List shelf = catalogue.shelf("classics"); + List titles = shelf.stream().map(Book::getTitle).toList(); + boolean ok = titles.equals(List.of("Beloved", "Middlemarch", "Rebecca")); + List lines = new ArrayList<>(); + lines.add("added: Beloved, Middlemarch, Rebecca. Then Beloved got a rating."); + lines.add("listed: " + String.join(", ", titles)); + if (!ok) { + lines.add("Not the order they were added in."); + } + return new Scenario(name, ok, lines); + } catch (RuntimeException e) { + return new Scenario(name, false, List.of(error(e))); + } + } + + private static void rated(CatalogueService catalogue, String title, String rating) { + Book book = catalogue.addBook(title, Format.PAPERBACK, "fiction"); + catalogue.rate(book.getId(), new BigDecimal(rating)); + } + + private static String describe(List books) { + return books.stream() + .map(book -> book.getTitle() + (book.getRating() == null ? " (no rating)" : " " + book.getRating())) + .collect(Collectors.joining(", ")); + } + + /** The database's own words: the first line of the deepest cause. */ + private static String error(Throwable throwable) { + Throwable deepest = throwable; + while (deepest.getCause() != null && deepest.getCause() != deepest) { + deepest = deepest.getCause(); + } + String message = deepest.getMessage() == null ? deepest.getClass().getSimpleName() : deepest.getMessage(); + return Report.shorten(message.lines().findFirst().orElse(message), 150); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java new file mode 100644 index 0000000..cbbb2f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/H2VersusPostgresIT.java @@ -0,0 +1,94 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.realdb.check.support.CheckPostgres; +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; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. These pass from the start: they pin down, with plain SQL, the differences between H2 and + * Postgres that the bugs in this project hide behind. Same statements, two databases. + */ +@Tag("task1") +class H2VersusPostgresIT { + + private static final String H2_POSTGRES_MODE = "jdbc:h2:mem:%s;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE"; + + @Test + @DisplayName("H2 vs Postgres: ORDER BY rating DESC puts the NULL rating last on H2 (PostgreSQL mode), first on Postgres") + void nullsInDescendingOrder() throws SQLException { + String[] setup = { + "create table book (id int primary key, title text, rating numeric(2,1))", + "insert into book values (1, 'Dune', 4.8), (2, 'No Reviews Yet', null), (3, 'Emma', 3.9)"}; + String query = "select title from book order by rating desc"; + + try (Connection h2 = h2("nulls"); Connection postgres = CheckPostgres.newDatabase("nulls")) { + assertThat(titles(h2, setup, query)).containsExactly("Dune", "Emma", "No Reviews Yet"); + assertThat(titles(postgres, setup, query)).containsExactly("No Reviews Yet", "Dune", "Emma"); + } + } + + @Test + @DisplayName("H2 vs Postgres: without ORDER BY, H2 returns rows by primary key, Postgres returns the row you just updated last") + void orderWithoutOrderBy() throws SQLException { + String[] setup = { + "create table book (id int primary key, title text, rating numeric(2,1))", + "insert into book values (1, 'Beloved', null), (2, 'Middlemarch', null), (3, 'Rebecca', null)", + "update book set rating = 4.5 where id = 1"}; + String query = "select title from book"; + + try (Connection h2 = h2("order"); Connection postgres = CheckPostgres.newDatabase("unordered")) { + assertThat(titles(h2, setup, query)).containsExactly("Beloved", "Middlemarch", "Rebecca"); + assertThat(titles(postgres, setup, query)).containsExactly("Middlemarch", "Rebecca", "Beloved"); + } + } + + @Test + @DisplayName("H2 vs Postgres: H2 cannot parse the real schema's index on lower(email) or ON CONFLICT (email); Postgres can, and rejects ON CONFLICT (email) because no index matches it") + void theRealSchemaAndTheUpsert() throws SQLException { + String table = "create table subscriber (id int generated by default as identity primary key, email text not null)"; + String index = "create unique index subscriber_email_key on subscriber (lower(email))"; + String upsert = "insert into subscriber (email) values ('ann@example.com') on conflict (email) do nothing"; + + try (Connection h2 = h2("schema"); Statement statement = h2.createStatement()) { + statement.execute(table); + assertThatThrownBy(() -> statement.execute(index)).hasMessageContaining("Syntax error"); + assertThatThrownBy(() -> statement.execute(upsert)).hasMessageContaining("Syntax error"); + } + try (Connection postgres = CheckPostgres.newDatabase("upsert"); Statement statement = postgres.createStatement()) { + statement.execute(table); + statement.execute(index); + assertThatThrownBy(() -> statement.execute(upsert)) + .hasMessageContaining("there is no unique or exclusion constraint matching the ON CONFLICT specification"); + } + } + + private static Connection h2(String name) throws SQLException { + return DriverManager.getConnection(H2_POSTGRES_MODE.formatted(name), "sa", ""); + } + + private static List titles(Connection connection, String[] setup, String query) throws SQLException { + try (Statement statement = connection.createStatement()) { + for (String sql : setup) { + statement.execute(sql); + } + List titles = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery(query)) { + while (rows.next()) { + titles.add(rows.getString(1)); + } + } + return titles; + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Inspect.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Inspect.java new file mode 100644 index 0000000..4059338 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Inspect.java @@ -0,0 +1,138 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.Recording.ContextInfo; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.sql.DataSource; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Runs your test suite once with a recorder attached and shows what it did underneath: the database + * each test class talked to, where its schema came from, how many Postgres containers and Spring + * contexts were started and how long each context took, and the rows left behind. Run it with + * ./inspect (or .\inspect on Windows). Needs Docker once your tests use Testcontainers. + */ +public final class Inspect { + + public static void main(String[] args) { + show(args); + // The Spring contexts of your tests are still cached, with their threads: end the JVM here. + StudentSuite.shutDown(); + System.exit(0); + } + + private static void show(String[] args) { + if (args.length > 0) { + System.out.println("Usage: ./inspect (Windows: .\\inspect)"); + System.out.println(); + System.out.println("Runs your test suite once and shows which databases, containers and Spring contexts it used."); + return; + } + String startedAt = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + List contexts = Recording.contexts(); + + System.out.println(); + System.out.println("TESTS (suite started at " + startedAt + ", took " + run.millis() + " ms)"); + Report.tests(run, "[PASS]", "[FAIL]"); + System.out.println(" " + run.tests().size() + " tests, " + run.passedCount() + " pass, " + run.failed().size() + " fail"); + + System.out.println(); + System.out.println("DATABASE EACH TEST CLASS USED"); + Report.databases(run); + + System.out.println(); + System.out.println("WHERE EACH SCHEMA CAME FROM"); + if (contexts.isEmpty()) { + System.out.println(" none of your tests started Spring"); + } + for (ContextInfo context : contexts) { + System.out.println(" context " + context.number + ": " + schema(context)); + } + + System.out.println(); + Map> servers = new LinkedHashMap<>(); + contexts.stream().filter(context -> context.database.serverId() != null) + .forEach(context -> servers.computeIfAbsent(context.database.serverId(), id -> new ArrayList<>()).add(context)); + System.out.println("POSTGRES SERVERS (one per container): " + servers.size()); + if (!servers.isEmpty()) { + List rows = new ArrayList<>(); + rows.add(new String[] {"server id", "started at", "used by contexts"}); + servers.forEach((id, users) -> rows.add(new String[] {id, users.get(0).database.serverStartedAt(), + users.stream().map(context -> String.valueOf(context.number)).collect(Collectors.joining(", "))})); + Report.table(rows); + } + + System.out.println(); + System.out.println("SPRING CONTEXTS STARTED: " + contexts.size()); + if (!contexts.isEmpty()) { + List rows = new ArrayList<>(); + rows.add(new String[] {"#", "kind", "start-up", "used by"}); + for (ContextInfo context : contexts) { + rows.add(new String[] {String.valueOf(context.number), context.kind, + String.format("%,d ms", context.loadMillis), + context.testClasses.stream().map(Class::getSimpleName).collect(Collectors.joining(", "))}); + } + Report.table(rows); + } + + System.out.println(); + System.out.println("ROWS LEFT BEHIND AFTER THE LAST TEST"); + List rows = new ArrayList<>(); + rows.add(new String[] {"context", "database", "book", "subscriber"}); + for (ContextInfo context : contexts) { + rows.add(leftBehind(context)); + } + if (rows.size() > 1) { + Report.table(rows); + } else { + System.out.println(" no database"); + } + System.out.println(); + } + + private static String schema(ContextInfo context) { + if (!context.isActive()) { + return "unknown: the context was closed (@DirtiesContext), its database with it"; + } + DataSource dataSource = context.dataSource(); + if (dataSource == null) { + return "no DataSource"; + } + if (!context.database.flywaySchema()) { + return "made up by Hibernate from the entities (no flyway_schema_history table)"; + } + List applied = new JdbcTemplate(dataSource).queryForList( + "select 'V' || version || ' ' || description from flyway_schema_history where success order by installed_rank", + String.class); + return "Flyway migrations " + String.join(", ", applied); + } + + private static String[] leftBehind(ContextInfo context) { + String database = Report.product(context.database); + if (!context.isActive()) { + return new String[] {String.valueOf(context.number), database, "gone", "(context closed)"}; + } + JdbcTemplate jdbc = new JdbcTemplate(context.dataSource()); + return new String[] {String.valueOf(context.number), database, count(jdbc, "book"), count(jdbc, "subscriber")}; + } + + private static String count(JdbcTemplate jdbc, String table) { + try { + return String.valueOf(jdbc.queryForObject("select count(*) from " + table, Long.class)); + } catch (RuntimeException e) { + return "no table"; + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/IsolationIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/IsolationIT.java new file mode 100644 index 0000000..88c9c69 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/IsolationIT.java @@ -0,0 +1,59 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.YourSuite; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 6: every test owns its data. Order, company and the value of a generated id do not matter. */ +@Tag("task6") +class IsolationIT { + + @Test + @DisplayName("Your suite: every test that passes in the full run also passes when it runs on its own") + void eachTestAlone() { + List broken = YourSuite.brokenBy(StudentSuite.eachAlone()); + if (!broken.isEmpty()) { + fail("These tests pass in the full run and fail on their own. They depend on what ran before them:" + + " data another test created, or rows nobody cleaned up:\n" + + String.join("\n", broken)); + } + } + + @Test + @DisplayName("Your suite: every test gives the same result with classes and methods run from Z to A") + void reverseOrder() { + Map reversed = YourSuite.byName(StudentSuite.run(Variant.REVERSED)); + List different = new ArrayList<>(); + for (TestResult test : StudentSuite.run(Variant.AS_IS).tests()) { + TestResult other = reversed.get(test.name()); + if (other != null && other.passed() != test.passed()) { + different.add(test.name() + (test.passed() ? " passes A to Z, fails Z to A: " + other.failure() + : " fails A to Z, passes Z to A: " + test.failure())); + } + } + if (!different.isEmpty()) { + fail("The order changes the result. Some test leaves data behind that another one trips over:\n" + + String.join("\n", different)); + } + } + + @Test + @DisplayName("Your suite: no test depends on the value of a generated id (every sequence moved on by 1000 before each test)") + void noGeneratedIdValues() { + List broken = YourSuite.brokenBy(YourSuite.byName(StudentSuite.run(Variant.SHIFTED_IDS))); + if (!broken.isEmpty()) { + fail("These tests pass in the first run and fail in this one:\n" + String.join("\n", broken) + + "\nA test that expects a literal id fails here: assert on the id the code gave back." + + " So does a test that trips over rows earlier runs left behind."); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java new file mode 100644 index 0000000..f037366 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/OneContainerIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.Recording.ContextInfo; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.YourSuite; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 5: one Postgres container and as few Spring contexts as possible for the whole suite. Counted, + * not timed: the probe records every context your suite starts and the Postgres server behind it. + */ +@Tag("task5") +class OneContainerIT { + + @BeforeEach + void runYourSuite() { + StudentSuite.run(Variant.AS_IS); + } + + @Test + @DisplayName("Your suite: every Spring test runs on PostgreSQL (no H2 left)") + void everySpringTestOnPostgres() { + List notPostgres = Recording.classes().entrySet().stream() + .filter(entry -> !entry.getValue().database.isPostgres()) + .map(entry -> entry.getKey().getSimpleName() + ": " + entry.getValue().database.describe()) + .toList(); + if (Recording.classes().isEmpty()) { + fail("None of your tests started Spring, so none of them ran on a database."); + } + if (!notPostgres.isEmpty()) { + fail("These test classes do not run on PostgreSQL:\n" + String.join("\n", notPostgres)); + } + } + + @Test + @DisplayName("Your suite: one Postgres container for the whole run, shared by every test class") + void oneContainer() { + List servers = Recording.contexts().stream() + .map(context -> context.database.serverId()) + .filter(Objects::nonNull) + .distinct() + .toList(); + if (servers.size() != 1) { + fail("Your tests talked to " + servers.size() + " Postgres servers (containers). Expected exactly 1.\n" + + YourSuite.databases()); + } + } + + @Test + @DisplayName("Your suite: at most 2 Spring contexts, one per kind of test (@DataJpaTest, @SpringBootTest)") + void fewContexts() { + List contexts = Recording.contexts(); + if (contexts.size() > 2) { + fail(contexts.size() + " Spring contexts were started. Test classes of the same kind should share one:\n" + + contexts.stream() + .map(context -> "context " + context.number + " " + context.kind + ": " + + context.testClasses.stream().map(Class::getSimpleName).collect(Collectors.joining(", "))) + .collect(Collectors.joining("\n")) + + "\nLook for what differs: properties, @Import, @DirtiesContext, @MockitoBean, @ActiveProfiles, the container."); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Report.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Report.java new file mode 100644 index 0000000..dd75be1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/Report.java @@ -0,0 +1,100 @@ +package com.amigoscode.realdb.check; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.test.context.BootstrapWith; + +/** Printing shared by ./demo and ./inspect. Plain ASCII, so it looks the same in every terminal. */ +final class Report { + + private Report() { + } + + static void tests(Run run, String green, String red) { + for (TestResult test : run.tests()) { + System.out.println(" " + (test.passed() ? green : red) + " " + test.name()); + if (!test.passed()) { + System.out.println(" " + shorten(test.failure(), 150)); + } + } + } + + /** One row per test class: the database it talked to, or that it started no Spring at all. */ + static void databases(Run run) { + Map, Recording.ContextInfo> spring = Recording.classes(); + Set classes = new LinkedHashSet<>(); + run.tests().forEach(test -> classes.add(test.className())); + List rows = new ArrayList<>(); + rows.add(new String[] {"test class", "database", "url"}); + for (String className : classes) { + String simple = className.substring(className.lastIndexOf('.') + 1); + Recording.ContextInfo context = spring.entrySet().stream() + .filter(entry -> entry.getKey().getName().equals(className)) + .map(Map.Entry::getValue) + .findFirst().orElse(null); + if (context == null && isSpringTest(className)) { + rows.add(new String[] {simple, "none", "its Spring context did not start (see the failure above)"}); + } else if (context == null) { + rows.add(new String[] {simple, "none", "no Spring context: a plain unit test"}); + } else { + rows.add(new String[] {simple, product(context.database), context.database.url()}); + } + } + table(rows); + } + + private static boolean isSpringTest(String className) { + try { + Class type = Class.forName(className); + return MergedAnnotations.from(type, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).isPresent(BootstrapWith.class); + } catch (ClassNotFoundException | LinkageError e) { + return false; + } + } + + static String product(Recording.DatabaseInfo database) { + if (database.product().equals("none")) { + return "no DataSource"; + } + String version = database.version().split(" ")[0]; + return database.product() + " " + version; + } + + static void table(List rows) { + 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()); + } + } + } + + static String shorten(String text, int max) { + if (text == null) { + return ""; + } + String ascii = text.replaceAll("[^\\x20-\\x7E]", "?"); + return ascii.length() <= max ? ascii : ascii.substring(0, max) + "..."; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java new file mode 100644 index 0000000..85f61f9 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/ShelfOrderIT.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import java.math.BigDecimal; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 7: an order you rely on is an ORDER BY you wrote, and a test that would notice without it. */ +@Tag("task7") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class ShelfOrderIT extends ProductionTest { + + @Test + @DisplayName("Production: a shelf lists its books in the order they were added, also after one of them is updated (on Postgres)") + void shelfOrderAfterAnUpdate() { + Book beloved = catalogue.addBook("Beloved", Format.PAPERBACK, "fiction"); + catalogue.addBook("Middlemarch", Format.HARDCOVER, "fiction"); + catalogue.addBook("Rebecca", Format.EBOOK, "fiction"); + catalogue.rate(beloved.getId(), new BigDecimal("4.5")); + + assertThat(titles(catalogue.shelf("fiction"))).containsExactly("Beloved", "Middlemarch", "Rebecca"); + } + + @Test + @DisplayName("Your suite: catches the missing ORDER BY (a test fails when findByShelf has no ORDER BY)") + void catchesTheMissingOrderBy() { + YourSuite.catches(Variant.SHELF_ORDER_BUG, + "On Postgres, update one of the books (rate it) before you read the shelf, and assert on the order."); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java new file mode 100644 index 0000000..aadcb30 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/SubscriptionIT.java @@ -0,0 +1,59 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import com.amigoscode.realdb.subscription.SubscriptionService.Outcome; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 4: the SQL behind subscribe is tested on Postgres, the service's logic keeps its fake. */ +@Tag("task4") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class SubscriptionIT extends ProductionTest { + + @Test + @DisplayName("Production: subscribing ann@example.com, then Ann@Example.COM, keeps one subscriber and answers ALREADY_SUBSCRIBED (on Postgres)") + void subscribeTwice() { + Outcome first = expectNoError("Subscribing ann@example.com", () -> subscriptions.subscribe("ann@example.com")); + Outcome second = expectNoError("Subscribing Ann@Example.COM", () -> subscriptions.subscribe("Ann@Example.COM")); + + assertThat(first).isEqualTo(Outcome.SUBSCRIBED); + assertThat(second).isEqualTo(Outcome.ALREADY_SUBSCRIBED); + assertThat(jdbc.queryForObject("select count(*) from subscriber", Integer.class)).isEqualTo(1); + } + + @Test + @DisplayName("Your suite: catches the ON CONFLICT bug (a test fails when subscribe uses ON CONFLICT (email))") + void catchesTheOnConflictBug() { + YourSuite.catches(Variant.ON_CONFLICT_BUG, + "Call SubscriberRepository.subscribe in a test that runs on Postgres with the Flyway schema." + + " The fake in SubscriptionServiceTest never runs the SQL."); + } + + @Test + @DisplayName("Your suite: SubscriptionServiceTest still tests the service's logic with the fake, with no Spring and no database") + void theFakeStaysForTheLogic() { + List tests = StudentSuite.run(Variant.AS_IS).tests().stream() + .filter(test -> test.simpleClassName().equals("SubscriptionServiceTest")) + .toList(); + if (tests.isEmpty()) { + fail("SubscriptionServiceTest is gone. Keep it: a fake is the right tool for the service's own logic" + + " (the email check, what 0 rows means). Only the SQL needs the database."); + } + assertThat(tests).as("SubscriptionServiceTest results").allMatch(TestResult::passed); + boolean startedSpring = Recording.classes().keySet().stream() + .anyMatch(type -> type.getSimpleName().equals("SubscriptionServiceTest")); + assertThat(startedSpring).as("SubscriptionServiceTest started a Spring context").isFalse(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java new file mode 100644 index 0000000..158ee8d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/TopRatedAndAudiobookIT.java @@ -0,0 +1,84 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.Format; +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import com.amigoscode.realdb.check.support.ProductionTest; +import com.amigoscode.realdb.check.support.YourSuite; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +/** Task 2: the repository tests run on Postgres, and the two bugs they find are fixed. */ +@Tag("task2") +@TestMethodOrder(MethodOrderer.DisplayName.class) +class TopRatedAndAudiobookIT extends ProductionTest { + + @Test + @DisplayName("Production: top rated lists the best rated books first, and never an unrated book ahead of a rated one (on Postgres)") + void topRated() { + rated("Dune", "4.8"); + catalogue.addBook("No Reviews Yet", Format.PAPERBACK, "fiction"); + rated("Emma", "3.9"); + catalogue.addBook("Brand New", Format.EBOOK, "fiction"); + rated("Hamlet", "4.2"); + + List top = catalogue.topRated(); + + assertThat(titles(top)).as("top rated").startsWith("Dune", "Hamlet", "Emma"); + } + + @Test + @DisplayName("Production: an AUDIOBOOK can be added (on Postgres, with the Flyway migrations)") + void audiobook() { + expectNoError("Adding an AUDIOBOOK", () -> catalogue.addBook("Dune", Format.AUDIOBOOK, "fiction")); + + assertThat(jdbc.queryForObject("select count(*) from book where format = 'AUDIOBOOK'", Integer.class)).isEqualTo(1); + } + + @Test + @DisplayName("Your suite: BookRepositoryTest runs on PostgreSQL, not H2") + void bookRepositoryTestOnPostgres() { + Recording.DatabaseInfo database = YourSuite.databaseOf("BookRepositoryTest"); + if (!database.isPostgres()) { + fail("BookRepositoryTest ran on " + database.describe()); + } + } + + @Test + @DisplayName("Your suite: BookRepositoryTest's schema comes from the Flyway migrations, not from Hibernate") + void bookRepositoryTestUsesTheMigrations() { + Recording.DatabaseInfo database = YourSuite.databaseOf("BookRepositoryTest"); + if (!database.flywaySchema()) { + fail("BookRepositoryTest's database has no flyway_schema_history table: Hibernate made the schema up" + + " from the entities.\nDatabase: " + database.describe()); + } + } + + @Test + @DisplayName("Your suite: catches the top rated bug (a test fails when findTopRated has no NULLS LAST)") + void catchesTheTopRatedBug() { + YourSuite.catches(Variant.TOP_RATED_BUG, + "Save a book without a rating next to rated ones, and assert on the order findTopRated returns, on Postgres."); + } + + @Test + @DisplayName("Your suite: catches the missing migration (a test fails when the database rejects AUDIOBOOK)") + void catchesTheMissingMigration() { + YourSuite.catches(Variant.MISSING_MIGRATION_BUG, + "Save an AUDIOBOOK in a test that runs on Postgres with the Flyway schema."); + } + + private void rated(String title, String rating) { + Book book = catalogue.addBook(title, Format.PAPERBACK, "fiction"); + catalogue.rate(book.getId(), new BigDecimal(rating)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java new file mode 100644 index 0000000..afa55cf --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/YourSuiteIT.java @@ -0,0 +1,24 @@ +package com.amigoscode.realdb.check; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Baseline. Your suite must be green on the code as it is: start/ is, and solution/ is. */ +@Tag("baseline") +class YourSuiteIT { + + @Test + @DisplayName("Your suite: every test passes on the code as it is") + void everyTestPasses() { + Run run = StudentSuite.run(StudentSuite.Variant.AS_IS); + if (!run.allPassed()) { + fail(run.failed().size() + " of " + run.tests().size() + " tests fail:\n" + + String.join("\n", run.failed().stream().map(test -> test.name() + ": " + test.failure()).toList())); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java new file mode 100644 index 0000000..1fd6a7f --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Mutant.java @@ -0,0 +1,85 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import javax.sql.DataSource; + +/** + * A bug from start/, put back into the fixed code while your test suite runs. A good suite fails when + * one of these is switched on: it "catches" the bug. Only the checks switch them on, never your + * normal test runs. + * + *

Three of them replace one repository method (see {@link MutantPostProcessor}). The fourth puts + * the database back the way it was before V2__allow_audiobooks.sql: it adds a constraint that rejects + * AUDIOBOOK, but only in a database whose schema was built by Flyway. A schema that Hibernate made up + * for H2 never had the migration in the first place. + */ +public enum Mutant { + + TOP_RATED("BookRepository.findTopRated without NULLS LAST: unrated books come first on Postgres"), + MISSING_MIGRATION("V2__allow_audiobooks.sql removed: the database rejects AUDIOBOOK"), + ON_CONFLICT("SubscriberRepository.subscribe with ON CONFLICT (email): no index matches it"), + SHELF_ORDER("BookRepository.findByShelf without ORDER BY: the database picks the order"); + + private static final String CONSTRAINT = "realdb_check_no_audiobook"; + + private static volatile Mutant active; + private static final Set CHANGED = Collections.newSetFromMap(new IdentityHashMap<>()); + + private final String description; + + Mutant(String description) { + this.description = description; + } + + public String description() { + return description; + } + + static Mutant active() { + return active; + } + + static void activate(Mutant mutant) { + active = mutant; + } + + /** Switches every mutant off and puts back any database that was changed. */ + static synchronized void deactivate() { + active = null; + for (DataSource dataSource : CHANGED) { + run(dataSource, "alter table book drop constraint if exists " + CONSTRAINT); + } + CHANGED.clear(); + } + + /** Called before each test class: puts the database bug into this context's database if needed. */ + static synchronized void prepareDatabase(DataSource dataSource, Recording.DatabaseInfo database) { + if (active != MISSING_MIGRATION || dataSource == null || CHANGED.contains(dataSource)) { + return; + } + if (!database.isPostgres() || !database.flywaySchema()) { + return; + } + run(dataSource, "alter table book drop constraint if exists " + CONSTRAINT); + run(dataSource, "alter table book add constraint " + CONSTRAINT + " check (format <> 'AUDIOBOOK') not valid"); + CHANGED.add(dataSource); + } + + private static void run(DataSource dataSource, String sql) { + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + connection.setAutoCommit(true); + statement.execute("set lock_timeout = '5s'"); + try { + statement.execute(sql); + } finally { + statement.execute("reset lock_timeout"); + } + } catch (Exception e) { + // The database is gone (its context was closed) or has no book table: nothing to change. + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java new file mode 100644 index 0000000..b165e1c --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantContextCustomizerFactory.java @@ -0,0 +1,39 @@ +package com.amigoscode.realdb.check.probe; + +import java.util.List; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ContextConfigurationAttributes; +import org.springframework.test.context.ContextCustomizer; +import org.springframework.test.context.ContextCustomizerFactory; +import org.springframework.test.context.MergedContextConfiguration; + +/** + * Registered in META-INF/spring.factories, so it takes part in every Spring test context. It adds + * {@link MutantPostProcessor} to the contexts of your tests (not to the checks' own contexts). It is + * the same for every test class, so it never stops two of your test classes from sharing a context. + */ +public class MutantContextCustomizerFactory implements ContextCustomizerFactory { + + @Override + public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { + return SuiteProbe.isYourTest(testClass) ? new Customizer() : null; + } + + private static final class Customizer implements ContextCustomizer { + + @Override + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { + context.getBeanFactory().addBeanPostProcessor(new MutantPostProcessor(context.getBeanFactory())); + } + + @Override + public boolean equals(Object other) { + return other instanceof Customizer; + } + + @Override + public int hashCode() { + return Customizer.class.hashCode(); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java new file mode 100644 index 0000000..e2523b1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/MutantPostProcessor.java @@ -0,0 +1,75 @@ +package com.amigoscode.realdb.check.probe; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.BookRepository; +import com.amigoscode.realdb.subscription.SubscriberRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.TypedQuery; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import javax.sql.DataSource; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.data.domain.Limit; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.ClassUtils; + +/** + * Wraps BookRepository and SubscriberRepository in every Spring context your tests start. While no + * {@link Mutant} is switched on, every call goes straight through to the real repository. While one is + * on, the one method it names runs the query from start/ instead. + */ +final class MutantPostProcessor implements BeanPostProcessor { + + private final ConfigurableListableBeanFactory beanFactory; + + MutantPostProcessor(ConfigurableListableBeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + if (bean instanceof BookRepository || bean instanceof SubscriberRepository) { + return Proxy.newProxyInstance(bean.getClass().getClassLoader(), + ClassUtils.getAllInterfaces(bean), (proxy, method, args) -> invoke(bean, method, args)); + } + return bean; + } + + private Object invoke(Object repository, Method method, Object[] args) throws Throwable { + Mutant mutant = Mutant.active(); + if (mutant == Mutant.TOP_RATED && method.getName().equals("findTopRated") && repository instanceof BookRepository) { + TypedQuery query = entityManager().createQuery("select b from Book b order by b.rating desc", Book.class); + if (args != null && args.length == 1 && args[0] instanceof Limit limit && limit.isLimited()) { + query.setMaxResults(limit.max()); + } + return query.getResultList(); + } + if (mutant == Mutant.SHELF_ORDER && method.getName().equals("findByShelf") && repository instanceof BookRepository) { + return entityManager().createQuery("select b from Book b where b.shelf = :shelf", Book.class) + .setParameter("shelf", args[0]) + .getResultList(); + } + if (mutant == Mutant.ON_CONFLICT && method.getName().equals("subscribe") && repository instanceof SubscriberRepository) { + TransactionTemplate transaction = new TransactionTemplate(beanFactory.getBean(PlatformTransactionManager.class)); + JdbcTemplate jdbc = new JdbcTemplate(beanFactory.getBean(DataSource.class)); + Integer rows = transaction.execute(status -> jdbc.update( + "insert into subscriber (email) values (?) on conflict (email) do nothing", args[0])); + return rows; + } + try { + return method.invoke(repository, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + private EntityManager entityManager() { + return SharedEntityManagerCreator.createSharedEntityManager(beanFactory.getBean(EntityManagerFactory.class)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Recording.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Recording.java new file mode 100644 index 0000000..07819b1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/Recording.java @@ -0,0 +1,174 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.sql.DataSource; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * What the probe saw while your test suite ran: every Spring context it started, how long that took, + * and which database each one was connected to. Filled by {@link SuiteProbe} during the first run of + * your suite in this JVM, read by the checks and by ./inspect. + */ +public final class Recording { + + /** One Spring application context that your tests used. */ + public static final class ContextInfo { + + public final int number; + public final String kind; + public final long loadMillis; + public final DatabaseInfo database; + public final List> testClasses = new ArrayList<>(); + final ApplicationContext context; + + ContextInfo(int number, String kind, long loadMillis, DatabaseInfo database, ApplicationContext context) { + this.number = number; + this.kind = kind; + this.loadMillis = loadMillis; + this.database = database; + this.context = context; + } + + public boolean isActive() { + return !(context instanceof ConfigurableApplicationContext configurable) || configurable.isActive(); + } + + public DataSource dataSource() { + return context.getBeanProvider(DataSource.class).getIfUnique(); + } + } + + /** + * The database behind a context's DataSource. {@code serverId} is Postgres's system identifier: every + * Postgres server (every container) has a different one. + */ + public record DatabaseInfo(String product, String version, String url, String serverId, String serverStartedAt, + boolean flywaySchema) { + + static final DatabaseInfo NONE = new DatabaseInfo("none", "", "", null, null, false); + + public boolean isPostgres() { + return product.equalsIgnoreCase("PostgreSQL"); + } + + public boolean isH2() { + return product.equalsIgnoreCase("H2"); + } + + public String describe() { + if (this == NONE) { + return "no DataSource"; + } + String name = isPostgres() ? "PostgreSQL " + version.split(" ")[0] : product + " " + version.split(" ")[0]; + return name + " " + url; + } + } + + private static volatile boolean active; + private static final Map CONTEXTS = new IdentityHashMap<>(); + private static final Map, ContextInfo> CLASSES = new LinkedHashMap<>(); + private static final Map DESCRIBED = new IdentityHashMap<>(); + + private Recording() { + } + + static boolean isActive() { + return active; + } + + static synchronized void start() { + CONTEXTS.clear(); + CLASSES.clear(); + active = true; + } + + static synchronized void stop() { + active = false; + } + + /** Called for every test instance. The first time a context is seen, the call to getApplicationContext loads it. */ + static synchronized ContextInfo seen(Class testClass, String kind, ApplicationContext context, long loadMillis) { + ContextInfo info = CONTEXTS.get(context); + if (info == null) { + info = new ContextInfo(CONTEXTS.size() + 1, kind, loadMillis, describeOnce(context), context); + CONTEXTS.put(context, info); + } + if (!CLASSES.containsKey(testClass)) { + CLASSES.put(testClass, info); + info.testClasses.add(testClass); + } + return info; + } + + /** Closes every context your tests used, in any run, so nothing is left to close at JVM exit. */ + static synchronized void closeAll() { + for (ApplicationContext context : DESCRIBED.keySet()) { + if (context instanceof ConfigurableApplicationContext configurable && configurable.isActive()) { + try { + configurable.close(); + } catch (RuntimeException e) { + // Closing is tidying up: nothing to report. + } + } + } + } + + /** The database behind a context, looked up once per context. */ + static synchronized DatabaseInfo describeOnce(ApplicationContext context) { + return DESCRIBED.computeIfAbsent(context, Recording::describe); + } + + /** Every context your suite started, in the order they were started. */ + public static synchronized List contexts() { + List all = new ArrayList<>(CONTEXTS.values()); + all.sort((a, b) -> Integer.compare(a.number, b.number)); + return all; + } + + /** Which context each Spring test class used. Test classes without Spring are not in here. */ + public static synchronized Map, ContextInfo> classes() { + return new LinkedHashMap<>(CLASSES); + } + + private static DatabaseInfo describe(ApplicationContext context) { + DataSource dataSource = context.getBeanProvider(DataSource.class).getIfUnique(); + if (dataSource == null) { + return DatabaseInfo.NONE; + } + try (Connection connection = dataSource.getConnection()) { + var meta = connection.getMetaData(); + String product = meta.getDatabaseProductName(); + String serverId = null; + String startedAt = null; + if (product.equalsIgnoreCase("PostgreSQL")) { + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery(""" + select system_identifier::text, + to_char(pg_postmaster_start_time(), 'HH24:MI:SS.MS') + from pg_control_system()""")) { + rows.next(); + serverId = rows.getString(1); + startedAt = rows.getString(2); + } + } + boolean flyway; + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery( + "select count(*) from information_schema.tables where lower(table_name) = 'flyway_schema_history'")) { + rows.next(); + flyway = rows.getInt(1) > 0; + } + return new DatabaseInfo(product, meta.getDatabaseProductVersion(), meta.getURL(), serverId, startedAt, flyway); + } catch (Exception e) { + return new DatabaseInfo("unknown (" + e.getClass().getSimpleName() + ")", "", "", null, null, false); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java new file mode 100644 index 0000000..0144b6d --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/StudentSuite.java @@ -0,0 +1,266 @@ +package com.amigoscode.realdb.check.probe; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUniqueId; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.ClassOrderer; +import org.junit.jupiter.api.ClassOrdererContext; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.MethodOrdererContext; +import org.junit.platform.engine.DiscoverySelector; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.discovery.ClassNameFilter; +import org.junit.platform.engine.support.descriptor.ClassSource; +import org.junit.platform.engine.support.descriptor.MethodSource; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +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 YOUR test suite: every test class under src/test/java/com/amigoscode/realdb, except the + * checks themselves in check/. Each way of running it happens at most once per JVM and is remembered, + * so ./check runs the suite a handful of times, not once per check. + */ +public final class StudentSuite { + + /** The ways the checks run your suite. */ + public enum Variant { + AS_IS("as it is, classes and methods from A to Z"), + AGAIN("as it is, a second time in the same JVM"), + REVERSED("classes and methods from Z to A"), + SHIFTED_IDS("with every id sequence moved on by 1000 just before each test"), + TOP_RATED_BUG("with the start/ version of findTopRated put back"), + MISSING_MIGRATION_BUG("with V2__allow_audiobooks.sql taken out of the database"), + ON_CONFLICT_BUG("with the start/ version of subscribe put back"), + SHELF_ORDER_BUG("with the start/ version of findByShelf put back"); + + private final String description; + + Variant(String description) { + this.description = description; + } + + public String description() { + return description; + } + } + + /** The outcome of one of your tests. */ + public record TestResult(String uniqueId, String className, String methodName, String displayName, + boolean passed, String failure) { + + public String simpleClassName() { + return className.substring(className.lastIndexOf('.') + 1); + } + + public String name() { + return simpleClassName() + (methodName == null ? "" : "." + methodName); + } + } + + /** All your tests, as one run reported them. */ + public record Run(List tests, long millis) { + + public boolean allPassed() { + return !tests.isEmpty() && tests.stream().allMatch(TestResult::passed); + } + + public List failed() { + return tests.stream().filter(test -> !test.passed()).toList(); + } + + public Optional find(String name) { + return tests.stream().filter(test -> test.name().equals(name)).findFirst(); + } + + public long passedCount() { + return tests.stream().filter(TestResult::passed).count(); + } + } + + private static final String ROOT_PACKAGE = "com.amigoscode.realdb"; + private static final Map RUNS = new EnumMap<>(Variant.class); + private static Map alone; + private static volatile boolean running; + + private StudentSuite() { + } + + /** Your suite, run one way. The first call of all is always AS_IS, and that is the run the probe records. */ + public static synchronized Run run(Variant variant) { + if (!RUNS.containsKey(Variant.AS_IS)) { + Recording.start(); + try { + RUNS.put(Variant.AS_IS, execute(List.of(selectPackage(ROOT_PACKAGE)), false)); + } finally { + Recording.stop(); + } + } + if (!RUNS.containsKey(variant)) { + RUNS.put(variant, runVariant(variant)); + } + return RUNS.get(variant); + } + + /** + * Call just before System.exit. Closes the Spring contexts your tests left in Spring's cache, with + * the output switched off: otherwise they close in a shutdown hook, and Hibernate prints its + * DROP TABLE statements after the last line of the report. + */ + public static void shutDown() { + System.out.flush(); + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + Recording.closeAll(); + } + + static boolean isRunning() { + return running; + } + + /** Every test that passed in the AS_IS run, run again on its own, one at a time. */ + public static synchronized Map eachAlone() { + if (alone == null) { + alone = new LinkedHashMap<>(); + for (TestResult test : run(Variant.AS_IS).tests()) { + if (test.passed() && test.methodName() != null) { + Run single = execute(List.of(selectUniqueId(test.uniqueId())), false); + single.tests().stream().findFirst().ifPresent(result -> alone.put(test.name(), result)); + } + } + } + return Collections.unmodifiableMap(alone); + } + + private static Run runVariant(Variant variant) { + List everything = List.of(selectPackage(ROOT_PACKAGE)); + switch (variant) { + case AGAIN -> { + return execute(everything, false); + } + case REVERSED -> { + return execute(everything, true); + } + case SHIFTED_IDS -> { + SuiteProbe.shiftIds(true); + try { + return execute(everything, false); + } finally { + SuiteProbe.shiftIds(false); + } + } + default -> { + Mutant.activate(switch (variant) { + case TOP_RATED_BUG -> Mutant.TOP_RATED; + case MISSING_MIGRATION_BUG -> Mutant.MISSING_MIGRATION; + case ON_CONFLICT_BUG -> Mutant.ON_CONFLICT; + case SHELF_ORDER_BUG -> Mutant.SHELF_ORDER; + default -> throw new IllegalArgumentException(variant.name()); + }); + try { + return execute(everything, false); + } finally { + Mutant.deactivate(); + } + } + } + } + + private static Run execute(List selectors, boolean reversed) { + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectors) + .filters(ClassNameFilter.includeClassNamePatterns(".*"), + ClassNameFilter.excludeClassNamePatterns(SuiteProbe.CHECK_PACKAGE.replace(".", "\\.") + "\\..*")) + .configurationParameter("junit.jupiter.testclass.order.default", + reversed ? ZToAClasses.class.getName() : ClassOrderer.ClassName.class.getName()) + .configurationParameter("junit.jupiter.testmethod.order.default", + reversed ? ZToAMethods.class.getName() : MethodOrderer.MethodName.class.getName()) + .build(); + Collector collector = new Collector(); + long started = System.nanoTime(); + Launcher launcher = LauncherFactory.create(); + // Your tests may print (Hibernate's SQL, Spring's banner). The checks print their own summary. + PrintStream out = System.out; + PrintStream err = System.err; + PrintStream nowhere = new PrintStream(OutputStream.nullOutputStream()); + System.setOut(nowhere); + System.setErr(nowhere); + running = true; + try { + launcher.execute(request, collector); + } finally { + running = false; + System.setOut(out); + System.setErr(err); + } + return new Run(List.copyOf(collector.results), (System.nanoTime() - started) / 1_000_000); + } + + private static final class Collector implements TestExecutionListener { + + private final List results = new ArrayList<>(); + + @Override + public void executionFinished(TestIdentifier test, TestExecutionResult result) { + boolean passed = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL; + String failure = result.getThrowable().map(StudentSuite::reason).orElse(null); + if (test.isTest()) { + if (test.getSource().orElse(null) instanceof MethodSource method) { + results.add(new TestResult(test.getUniqueId(), method.getClassName(), method.getMethodName(), + test.getDisplayName(), passed, failure)); + } + } else if (!passed && test.getSource().orElse(null) instanceof ClassSource source) { + // The class itself failed, for example its container or its Spring context did not start. + results.add(new TestResult(test.getUniqueId(), source.getClassName(), null, + test.getDisplayName() + " could not start", false, failure)); + } + } + } + + /** For an assertion, its message. Otherwise the deepest cause with a message: usually the database's own words. */ + static String reason(Throwable throwable) { + String message = throwable.getMessage(); + if (!(throwable instanceof AssertionError)) { + for (Throwable cause = throwable; cause != null; cause = cause.getCause() == cause ? null : cause.getCause()) { + if (cause.getMessage() != null && !cause.getMessage().isBlank()) { + message = cause.getMessage(); + } + } + } + if (message == null) { + return throwable.getClass().getSimpleName(); + } + return String.join(" ", message.strip().lines().map(String::strip).filter(line -> !line.isEmpty()).limit(4).toList()); + } + + /** Classes from Z to A. */ + public static final class ZToAClasses implements ClassOrderer { + + @Override + public void orderClasses(ClassOrdererContext context) { + context.getClassDescriptors().sort((a, b) -> b.getTestClass().getName().compareTo(a.getTestClass().getName())); + } + } + + /** Methods from Z to A. A class with its own @TestMethodOrder keeps its own order. */ + public static final class ZToAMethods implements MethodOrderer { + + @Override + public void orderMethods(MethodOrdererContext context) { + context.getMethodDescriptors().sort((a, b) -> b.getMethod().getName().compareTo(a.getMethod().getName())); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java new file mode 100644 index 0000000..0b9419b --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/probe/SuiteProbe.java @@ -0,0 +1,102 @@ +package com.amigoscode.realdb.check.probe; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.concurrent.atomic.AtomicLong; +import javax.sql.DataSource; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.JdbcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.test.context.TestContext; +import org.springframework.test.context.TestExecutionListener; + +/** + * A Spring TestExecutionListener, registered in META-INF/spring.factories, so Spring runs it for every + * Spring test, yours included. It does nothing unless a check, ./demo or ./inspect is running your + * suite. Then it records which context each test class used and which database that context talks + * to, and it can put a bug back in ({@link Mutant}) or move the id sequences on. + */ +public class SuiteProbe implements TestExecutionListener, Ordered { + + static final String CHECK_PACKAGE = "com.amigoscode.realdb.check"; + + private static volatile boolean shiftIds; + private static final AtomicLong H2_RESTART = new AtomicLong(1_000_000); + + static boolean isYourTest(Class testClass) { + return !testClass.getName().startsWith(CHECK_PACKAGE + "."); + } + + static void shiftIds(boolean on) { + shiftIds = on; + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public void prepareTestInstance(TestContext testContext) { + Class testClass = testContext.getTestClass(); + if (!isYourTest(testClass) || !StudentSuite.isRunning()) { + return; + } + long started = System.nanoTime(); + ApplicationContext context = testContext.getApplicationContext(); + long loadMillis = (System.nanoTime() - started) / 1_000_000; + Recording.DatabaseInfo database; + if (Recording.isActive()) { + database = Recording.seen(testClass, kind(testClass), context, loadMillis).database; + } else { + database = Recording.describeOnce(context); + } + Mutant.prepareDatabase(context.getBeanProvider(DataSource.class).getIfUnique(), database); + } + + @Override + public void beforeTestExecution(TestContext testContext) { + if (!shiftIds || !isYourTest(testContext.getTestClass())) { + return; + } + DataSource dataSource = testContext.getApplicationContext().getBeanProvider(DataSource.class).getIfUnique(); + if (dataSource == null) { + return; + } + try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { + connection.setAutoCommit(true); + String product = connection.getMetaData().getDatabaseProductName(); + for (String table : new String[] {"book", "subscriber"}) { + try { + if (product.equalsIgnoreCase("PostgreSQL")) { + statement.execute("select setval(pg_get_serial_sequence('" + table + "', 'id'), " + + "nextval(pg_get_serial_sequence('" + table + "', 'id')) + 1000)"); + } else { + statement.execute("alter table " + table + " alter column id restart with " + H2_RESTART.addAndGet(1000)); + } + } catch (Exception e) { + // No such table in this context: nothing to move on. + } + } + } catch (Exception e) { + // The database is not reachable: the test will say so itself. + } + } + + static String kind(Class testClass) { + MergedAnnotations annotations = MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY); + if (annotations.isPresent(DataJpaTest.class)) { + return "@DataJpaTest"; + } + if (annotations.isPresent(JdbcTest.class)) { + return "@JdbcTest"; + } + if (annotations.isPresent(SpringBootTest.class)) { + return "@SpringBootTest"; + } + return "Spring test"; + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java new file mode 100644 index 0000000..6c5bb03 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/CheckPostgres.java @@ -0,0 +1,37 @@ +package com.amigoscode.realdb.check.support; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The checks' own Postgres, separate from the one your tests start. It is started once, the first + * time a check needs it, and Testcontainers removes it when the JVM ends. + */ +public final class CheckPostgres { + + private static PostgreSQLContainer container; + + private CheckPostgres() { + } + + public static synchronized PostgreSQLContainer container() { + if (container == null) { + container = new PostgreSQLContainer("postgres:17-alpine"); + container.start(); + } + return container; + } + + /** A plain JDBC connection to an empty database of its own, for the checks that compare H2 and Postgres. */ + public static Connection newDatabase(String name) throws SQLException { + PostgreSQLContainer postgres = container(); + try (Connection admin = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + admin.createStatement().execute("drop database if exists " + name); + admin.createStatement().execute("create database " + name); + } + String url = postgres.getJdbcUrl().replace("/" + postgres.getDatabaseName(), "/" + name); + return DriverManager.getConnection(url, postgres.getUsername(), postgres.getPassword()); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java new file mode 100644 index 0000000..93a2334 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/ProductionTest.java @@ -0,0 +1,60 @@ +package com.amigoscode.realdb.check.support; + +import com.amigoscode.realdb.catalogue.Book; +import com.amigoscode.realdb.catalogue.CatalogueService; +import com.amigoscode.realdb.subscription.SubscriptionService; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * Base class for the checks that ask "does the code in src/main work on real Postgres?". It runs the + * whole application, with the Flyway migrations, against the checks' own Postgres, the way production + * would. It does not look at your tests at all. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = "spring.main.banner-mode=off") +public abstract class ProductionTest { + + @DynamicPropertySource + static void database(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", () -> CheckPostgres.container().getJdbcUrl()); + registry.add("spring.datasource.username", () -> CheckPostgres.container().getUsername()); + registry.add("spring.datasource.password", () -> CheckPostgres.container().getPassword()); + } + + @Autowired + protected CatalogueService catalogue; + + @Autowired + protected SubscriptionService subscriptions; + + @Autowired + protected JdbcTemplate jdbc; + + @BeforeEach + void emptyDatabase() { + jdbc.execute("truncate table book, subscriber restart identity"); + } + + protected static List titles(List books) { + return books.stream().map(Book::getTitle).toList(); + } + + /** Runs the action, and turns an exception into a failure that quotes the database's own words. */ + protected static T expectNoError(String what, java.util.function.Supplier action) { + try { + return action.get(); + } catch (RuntimeException e) { + Throwable deepest = e; + while (deepest.getCause() != null && deepest.getCause() != deepest) { + deepest = deepest.getCause(); + } + String message = String.valueOf(deepest.getMessage()); + throw new AssertionError(what + " failed on Postgres:\n" + message.lines().findFirst().orElse(message)); + } + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java new file mode 100644 index 0000000..f67c2e7 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/UrlFromProperties.java @@ -0,0 +1,22 @@ +package com.amigoscode.realdb.check.support; + +import java.util.Map; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; + +/** + * Puts the checks' Postgres URL into the environment as an ordinary property source, the way + * application.properties would. (A @DynamicPropertySource URL is treated differently by @DataJpaTest.) + */ +public class UrlFromProperties implements ApplicationContextInitializer { + + @Override + public void initialize(ConfigurableApplicationContext context) { + var postgres = CheckPostgres.container(); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("like-application-properties", Map.of( + "spring.datasource.url", postgres.getJdbcUrl(), + "spring.datasource.username", postgres.getUsername(), + "spring.datasource.password", postgres.getPassword()))); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java new file mode 100644 index 0000000..e93d5f2 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/check/support/YourSuite.java @@ -0,0 +1,84 @@ +package com.amigoscode.realdb.check.support; + +import static org.assertj.core.api.Assertions.fail; + +import com.amigoscode.realdb.check.probe.Recording; +import com.amigoscode.realdb.check.probe.StudentSuite; +import com.amigoscode.realdb.check.probe.StudentSuite.Run; +import com.amigoscode.realdb.check.probe.StudentSuite.TestResult; +import com.amigoscode.realdb.check.probe.StudentSuite.Variant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** The questions the checks ask about YOUR test suite, with failure messages that say what to do. */ +public final class YourSuite { + + private YourSuite() { + } + + /** + * Passes if at least one test that is green on the current code turns red with the bug put back. + * That is what "your tests catch the bug" means. A test only counts if it is also green when the + * suite runs a second time without the bug: then the bug, and nothing else, turned it red. + */ + public static void catches(Variant bug, String hint) { + Run asIs = StudentSuite.run(Variant.AS_IS); + Run again = StudentSuite.run(Variant.AGAIN); + Run withBug = StudentSuite.run(bug); + List caughtBy = new ArrayList<>(); + List unstable = new ArrayList<>(); + for (TestResult test : asIs.tests()) { + boolean greenAgain = again.find(test.name()).map(TestResult::passed).orElse(false); + if (test.passed() && !greenAgain) { + unstable.add(test.name() + ": " + again.find(test.name()).map(TestResult::failure).orElse("did not run")); + } else if (test.passed() && withBug.find(test.name()).map(result -> !result.passed()).orElse(false)) { + caughtBy.add(test.name()); + } + } + if (caughtBy.isEmpty()) { + fail("Your suite ran " + bug.description() + ", and no test that passes now failed." + + "\nSo it would not catch this bug. " + hint + + (unstable.isEmpty() ? "" : "\nThese tests do not count: they fail when the suite runs a second time," + + " even without the bug:\n" + String.join("\n", unstable))); + } + } + + /** Which database each of your Spring test classes talked to, as "Class: database". */ + public static String databases() { + Map, Recording.ContextInfo> classes = Recording.classes(); + if (classes.isEmpty()) { + return "(none of your test classes started Spring)"; + } + return classes.entrySet().stream() + .map(entry -> entry.getKey().getSimpleName() + ": " + entry.getValue().database.describe()) + .collect(Collectors.joining("\n")); + } + + public static Recording.DatabaseInfo databaseOf(String simpleClassName) { + StudentSuite.run(Variant.AS_IS); + return Recording.classes().entrySet().stream() + .filter(entry -> entry.getKey().getSimpleName().equals(simpleClassName)) + .map(entry -> entry.getValue().database) + .findFirst() + .orElseGet(() -> fail(simpleClassName + " did not start a Spring context, or does not exist." + + "\nIt should be a @DataJpaTest in src/test/java/com/amigoscode/realdb/.")); + } + + /** Tests that passed in the normal run and failed in the other one. */ + public static List brokenBy(Map other) { + List broken = new ArrayList<>(); + for (TestResult test : StudentSuite.run(Variant.AS_IS).tests()) { + TestResult result = other.get(test.name()); + if (test.passed() && result != null && !result.passed()) { + broken.add(test.name() + ": " + result.failure()); + } + } + return broken; + } + + public static Map byName(Run run) { + return run.tests().stream().collect(Collectors.toMap(TestResult::name, test -> test, (a, b) -> a)); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java new file mode 100644 index 0000000..e3dd27e --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/FakeSubscriberRepository.java @@ -0,0 +1,24 @@ +package com.amigoscode.realdb.subscription; + +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +/** + * An in-memory stand-in for SubscriberRepository. Its query uses ON CONFLICT, which H2 cannot run, + * so the service is tested with this instead. + */ +class FakeSubscriberRepository implements SubscriberRepository { + + private final Set addresses = new HashSet<>(); + + @Override + public int subscribe(String email) { + return addresses.add(email.toLowerCase(Locale.ROOT)) ? 1 : 0; + } + + @Override + public long count() { + return addresses.size(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java new file mode 100644 index 0000000..ab38061 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/java/com/amigoscode/realdb/subscription/SubscriptionServiceTest.java @@ -0,0 +1,35 @@ +package com.amigoscode.realdb.subscription; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.realdb.subscription.SubscriptionService.Outcome; +import org.junit.jupiter.api.Test; + +/** Subscriptions, with a fake repository: no Spring, no database, a few milliseconds. */ +class SubscriptionServiceTest { + + private final FakeSubscriberRepository subscribers = new FakeSubscriberRepository(); + private final SubscriptionService service = new SubscriptionService(subscribers); + + @Test + void aNewAddressIsSubscribed() { + assertThat(service.subscribe("ann@example.com")).isEqualTo(Outcome.SUBSCRIBED); + } + + @Test + void theSameAddressInAnyCapitalisationIsSubscribedOnlyOnce() { + service.subscribe("ann@example.com"); + + assertThat(service.subscribe("Ann@Example.com")).isEqualTo(Outcome.ALREADY_SUBSCRIBED); + assertThat(subscribers.count()).isEqualTo(1); + } + + @Test + void rejectsSomethingThatIsNotAnEmailAddress() { + assertThatThrownBy(() -> service.subscribe("ann at example dot com")) + .isInstanceOf(InvalidEmailException.class); + + assertThat(subscribers.count()).isZero(); + } +} diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/META-INF/spring.factories b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/META-INF/spring.factories new file mode 100644 index 0000000..3f7b152 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +# Part of the acceptance checks (src/test/java/com/amigoscode/realdb/check). Do not edit. +# Both do nothing during a normal test run. See check/probe/SuiteProbe.java. +org.springframework.test.context.TestExecutionListener=\ +com.amigoscode.realdb.check.probe.SuiteProbe +org.springframework.test.context.ContextCustomizerFactory=\ +com.amigoscode.realdb.check.probe.MutantContextCustomizerFactory diff --git a/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..1785fb1 --- /dev/null +++ b/java/concepts/junior-mid/17-testing-with-a-real-database/start/src/test/resources/logback-test.xml @@ -0,0 +1,15 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + + + + diff --git a/java/concepts/junior-mid/18-virtual-threads/INTERVIEW_TASKS.md b/java/concepts/junior-mid/18-virtual-threads/INTERVIEW_TASKS.md new file mode 100644 index 0000000..3cdc074 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/INTERVIEW_TASKS.md @@ -0,0 +1,271 @@ +# Interview Tasks — Virtual Threads + +> **In `start/`, `./check` FAILS on purpose: 17 of 25 checks pass.** Tasks 2, 4, 5 and 7 turn the +> other 8 green. Tasks 1, 3, 6 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 +`server.tomcat.threads.max` or the pool size in `application.properties` to make a test pass. Do not +fix the exhibit (`PooledFareController`): it stays as it is so you can compare against it. + +--- + +## Task 1: See the Thread-per-Request Ceiling (10 min) + +**Story:** *Every Monday at 9:00 the marketing email goes out and 200 people search for flights at +once. Searches take seconds, and even the route list, one tiny query, hangs. The airline answers in +half a second, the database is idle. Find out where the time goes before you change anything.* + +**Steps:** +1. `docker compose up -d`, then `./demo`. How many searches were in flight at the same moment? How + many waited, and where? How long did the run take, and why roughly that long? +2. Read the "Served by" line. How many threads served 200 requests? What kind of thread? +3. Read "A fast GET /api/routes sent during the load". Why did a 3 ms request take seconds? +4. `./demo --requests 500`. Predict the time taken before you run it. +5. Open `application.properties`. Which line explains step 1? What is its default value in Spring + Boot, and what would change with the default? +6. What is a thread doing while its request waits for the airline? + +**Acceptance Criteria** (`./check 1`, already passing: these tests document the ceiling) +- [ ] You can explain the thread-per-request model in two sentences +- [ ] You can say why the 21st request waits, and where it waits +- [ ] You can explain why a fast request is slow when the slow ones fill the pool +- [ ] You can say why "just raise the thread count to 10,000" is not the answer with platform threads +- [ ] `PlatformThreadsIT` passes + +**Hints:** +- Total time is about (requests / threads) x 500 ms +- A platform thread is an OS thread. Look up what one costs in memory and in scheduling + +--- + +## Task 2: Turn On Virtual Threads (5 min) + +**Story:** *You read that Java 21 brought virtual threads and that Spring Boot supports them. Turn +them on. Keep `server.tomcat.threads.max=20` as it is.* + +**Acceptance Criteria** (`./check 2`) +- [ ] 50 slow searches are all in flight at the same moment + — `VirtualThreadsIT.allFiftyInFlight` +- [ ] Every request is served by a virtual thread — `VirtualThreadsIT.servedByVirtualThreads` +- [ ] The request threads run on a few carrier threads, fewer than the requests + — `VirtualThreadsIT.aFewCarrierThreads` +- [ ] `./demo` shows 200 requests in flight at once. (Look at the `RESULT` line too. It is the start + of Task 4.) + +**Hints:** +- One property in `application.properties` +- After the change, look at "Requests waiting in Tomcat's queue" and at the thread names + +--- + +## Task 3: Inspect Virtual Threads (20 min) + +**Story:** *A colleague asks three questions: "Where did the limit of 20 go? If there is no pool, +what runs these threads? And does this make our pricing engine faster too?"* + +**Steps:** +1. `./inspect`. Read "Threads holding them" and the three `Thread.toString()` lines. What is + missing from a blocked virtual thread's `toString()` compared with `./demo`'s carrier names? +2. Read "Virtual threads mounted on a carrier now". 50 requests are in flight. How many carrier + threads are busy? What does "unmounted" mean? +3. Read "Carriers they started on" and "CPU cores". What decides the number of carrier threads? +4. Compare "Platform threads in the whole JVM" with `./inspect --virtual off`. What happened to the + 20 Tomcat threads? +5. `./demo --scenario cpu`. Compare "In flight at once" and "Time taken" on platform and virtual + threads. Why are only as many requests in flight as you have cores? +6. `./check 3`. What do the two tests prove about a blocked virtual thread? + +**Acceptance Criteria** (no code; `./check 3` passes from the start) +- [ ] You can explain mount, unmount and carrier thread in your own words +- [ ] You can say why a blocking call is cheap on a virtual thread and expensive on a platform thread +- [ ] You can say why CPU-bound work gains nothing +- [ ] You can say what a virtual thread costs, compared with a platform thread + +--- + +## Task 4: Fix the New Bottleneck: the Connection Pool (20 min) + +**Story:** *Virtual threads went to staging and the error rate went up: 503s with "Connection is not +available, request timed out after 2000ms". Nothing changed in the database. Fix `FareService`.* + +**Steps before you change anything:** +1. `./demo`. How many searches failed, and with what? How many waited for a connection at the peak? +2. `./inspect`. What does Postgres say the 20 connections are doing? What is each one waiting for? +3. Try the obvious fix: `./demo --pool-size 200`. How many connections did the pool really get? Why + that number? (`./inspect` prints `max_connections`.) What fails now instead? + +**Acceptance Criteria** (`./check 4`) +- [ ] While 30 searches wait for the airline, none of them holds a database connection + — `ConnectionPoolIT.noConnectionHeldWhileWaitingForTheAirline` +- [ ] 30 searches at the same moment, a pool of 10: every search gets a fare + — `ConnectionPoolIT.nobodyTimesOutWaitingForAConnection` +- [ ] Every search is still saved — `ConnectionPoolIT.everySearchIsSaved` + (already passing: keep it that way) +- [ ] `./demo` has no `DB_POOL_TIMEOUT` any more. (It has a new problem. That is Task 5.) + +**Hints:** +- When does a `@Transactional` method take its connection, and when does it give it back? +- Does anything in `search` need to be atomic? If it did, how would you keep a transaction without + holding it across the airline call? +- Do not touch the pool size + +--- + +## Task 5: Limit the Airline Calls, Not the Threads (20 min) + +**Story:** *The 503s are now "The airline answered 429 Too Many Requests". The airline's contract +says 50 calls in progress at once; Tomcat's 20 threads used to keep you under it without anyone +knowing. Make `FareService` send at most `fares.max-airline-calls` calls at once. A search over the +limit waits for its turn. It must not fail and must not move to another thread.* + +**Acceptance Criteria** (`./check 5`) +- [ ] 15 searches, the airline allows 5: it never has more than 5 calls in progress + — `AirlineLimitIT.neverMoreThanFiveAtTheAirline` +- [ ] All 15 get a fare — `AirlineLimitIT.everySearchGetsAFare` +- [ ] The call runs on the request's own virtual thread, not in a thread pool + — `AirlineLimitIT.calledOnTheRequestThread` (already passing: keep it that way) +- [ ] A failed call gives its slot back — `AirlineLimitIT.aFailedCallGivesItsSlotBack` + (already passing: keep it that way) +- [ ] `./demo` prints `RESULT: OK` + +**Hints:** +- `java.util.concurrent` has a class that hands out N permits +- What happens to a permit when `airline.quote` throws? +- Do not use `tryAcquire` without a wait: that turns "wait your turn" into "fail" + +--- + +## Task 6: Inspect the Limits (20 min) + +**Story:** *In the design review someone asks: "Why not raise the pool? Why not a thread pool of 50 +for the airline, like we always did? And what about our `@Async` jobs?"* + +**Steps:** +1. `./inspect`. What do the 20 connections do now while 50 searches wait? Compare with Task 4 step 2. +2. You tried `--pool-size 200` in Task 4. What did Postgres do, and why is a pool that big a bad idea + even when the database allows it? +3. `./demo --scenario pooled`. It limits the airline calls with `Executors.newFixedThreadPool(50)`. + It works. Compare "Airline called from" and "Platform threads in the JVM" with `./demo`. List + three things this pool brings back. +4. In `./inspect`, read "@Async and applicationTaskExecutor" and "An @Async method ran on". Then + `./inspect --virtual off`. What does Spring Boot use for `@Async` in each case? Which one has a + limit? +5. `./demo --virtual off`. Compare time taken with `./demo`. Where does the remaining time go? + +**Acceptance Criteria** (no tests: you answer) +- [ ] You can explain why a connection pool should stay small, with numbers from this project +- [ ] You can say why "do not pool virtual threads" and how to limit concurrency instead +- [ ] You can name every limit the platform thread pool was hiding in this application +- [ ] You can say what `spring.threads.virtual.enabled` changes besides Tomcat + +--- + +## Task 7: Fix the ThreadLocal Cache (15 min) + +**Story:** *After the switch, memory use went up and the garbage collector got busy. A heap profile +points at `RateTable`: hundreds of them. Fix `ExchangeRates`.* + +**Acceptance Criteria** (`./check 7`) +- [ ] 20 searches on virtual threads build the rate table at most once + — `RateTableOnVirtualThreadsIT.builtAtMostOnce` +- [ ] On 20 platform threads, 50 searches build it at most 20 times + — `RateTableOnPlatformThreadsIT.builtAtMostOncePerPooledThread` (already passing) +- [ ] The conversions stay correct, from any number of threads + — `ExchangeRatesTest.convertsFromAnyThread` (already passing: keep it that way) +- [ ] `./demo` shows "Rate tables built during the run: 0" + +**Hints:** +- Before you change it: `./demo` and `./demo --virtual off`. Compare "Rate tables built" +- Can two threads use one `RateTable` at the same time? Look for anything that writes to it after + the constructor +- What would you use instead of a `ThreadLocal` to pass the current customer down a call? + +--- + +## Task 8: Inspect Pinning, and Decide (20 min) + +**Story:** *A blog post from 2023 says "never use `synchronized` with virtual threads, it pins the +carrier". Your codebase is full of `synchronized`. Find out what is true on Java 25, and finish with +a recommendation: virtual threads, platform threads or WebFlux.* + +**Steps:** +1. `./demo --scenario pinning`. Which cases pin? Read the reasons JFR gives. +2. In the static initializer case, JFR saw as many pinned threads as you have cores, not as many as + were started. Where were the others? +3. Why does the native case take about twice as long as the others? +4. `./check 8`. How do these tests know that a thread was pinned, without measuring time? +5. Look at the PINNING section of every `./inspect` you ran. When did pinned events appear, and in + which code? Do they come back on the second run of the same code? +6. `-Djdk.tracePinnedThreads=full` was the Java 21 way to find pinning. What is the Java 25 way? +7. Write down when you would use virtual threads, when not, and how you would answer "virtual + threads or WebFlux?". + +**Acceptance Criteria** (no code; `./check 8` passes from the start) +- [ ] You can define pinning and say why it matters with only a few carrier threads +- [ ] You can say what changed in Java 24 (JEP 491) and what still pins on Java 25 +- [ ] You can name the JFR event to look for +- [ ] You can give one workload where virtual threads help and one where they do not + +--- + +## Questions to Ask Afterwards + +Answer out loud, in full sentences, before reading the answer in brackets. + +- What is a virtual thread? (A `java.lang.Thread` that the JVM schedules, not the OS. It is an + object on the heap. It runs mounted on a carrier, a platform thread of a `ForkJoinPool`. When it + blocks on I/O, a lock or a sleep, the JVM saves its stack to the heap and unmounts it, and the + carrier runs another virtual thread.) +- Do virtual threads make code faster? (No. Each request takes as long as before. They raise how + many requests can wait at the same time, so throughput goes up when the work is mostly waiting on + I/O. CPU-bound work gains nothing: the cores are the limit.) +- How do you turn them on in Spring Boot? (`spring.threads.virtual.enabled=true`, Java 21 or later. + Tomcat then starts a virtual thread per request, and `@Async`, the task scheduler and other + auto-configured executors use virtual threads too.) +- Should you pool virtual threads? (No. They are cheap to create and meant to be used once per task. + A pool exists to reuse expensive threads and to limit concurrency. To limit, use a `Semaphore` + around the scarce resource, or the resource's own pool, like HikariCP for connections.) +- What happens to the connection pool when you switch? (It becomes the real limit. With 20 platform + threads at most 20 requests could ask for a connection. With virtual threads all of them can, and + any code that holds a connection while it waits for something slow exhausts the pool.) +- Why not make the pool as big as the number of requests? (The database has a hard limit, + `max_connections`, 100 by default in Postgres, shared by every instance of the service. Each + connection is a process with its own memory in Postgres, and more connections running at once make + the database slower, not faster. Keep the pool small and hold connections briefly.) +- What is pinning? (A virtual thread that cannot unmount while it blocks, so it keeps its carrier + busy. With one carrier per core, a few pinned threads can stop all the others.) +- Does `synchronized` still pin? (Not since Java 24, JEP 491. On Java 21 to 23 it did, which is why + older advice says to replace it with `ReentrantLock`. On Java 25 a virtual thread still pins when + it blocks inside a class initializer, waits for another thread's class initializer, or blocks with + a native frame on its stack. JFR's `jdk.VirtualThreadPinned` event reports each case.) +- Why is a `ThreadLocal` cache a problem? (A virtual thread usually serves one task and ends, so a + per-thread cache is built for every task and never reused, and there can be millions of threads. + Share an immutable or thread-safe object instead. To pass request data, use `ScopedValue`, final + in Java 25.) +- Virtual threads or WebFlux? (Both let a few OS threads serve many waiting requests. Virtual + threads keep plain blocking code, normal stack traces and the libraries you know, like JDBC. + WebFlux makes every call non-blocking, which pays off for streaming and end-to-end backpressure, + and when the code is already reactive. For a typical CRUD service on Java 21+, virtual threads.) + +## Tips for Interviewers + +- The most common wrong answer is "virtual threads are faster threads". Ask what happens to a + CPU-bound endpoint, and what happens to the 201st request when the pool has 200 connections. +- Ask the candidate to predict `./demo` right after Task 2. Most expect `RESULT: OK`. A strong + candidate asks what the request holds while it waits, and finds the transaction. +- Watch how they limit the airline in Task 5. `newFixedThreadPool(50)` passes three of the four + checks, and `tryAcquire()` without a timeout fails one. Ask them why `release()` goes in `finally`. +- In Task 8, a candidate who says "replace every `synchronized` with `ReentrantLock`" is quoting Java + 21 advice. Ask them how they would find out on Java 25. The answer is JFR, not a blog post. +- For senior candidates: "What is still limited after all these fixes?" (the airline, the database, + memory per in-flight request) and "what would you monitor after the switch?" (pool waiting count, + pinned events, heap, downstream 429s). diff --git a/java/concepts/junior-mid/18-virtual-threads/README.md b/java/concepts/junior-mid/18-virtual-threads/README.md new file mode 100644 index 0000000..79cb4a7 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/README.md @@ -0,0 +1,205 @@ +# Virtual Threads — Java 25 and Spring Boot 4 + +> **In `start/`, `./check` FAILS on purpose: 17 of 25 checks pass.** That is the exercise, not a +> broken checkout. Tasks 2, 4, 5 and 7 turn the other 8 green. + +A flight search waits half a second for the airline on every request. 200 customers search at the +same moment, and Tomcat serves them **20 at a time**: the other 180 wait in a queue, and so does a +request that would have taken 3 ms. You turn on virtual threads with one property, all 200 are +served at once... and 120 of them fail, because the connection pool was the next thing in line. + +This project lets you watch the thread-per-request ceiling, lift it, then find every limit the +thread pool used to hide: the connection pool, a partner API's rate limit, a `ThreadLocal` cache. +And it shows you, on your own JVM, what still pins a virtual thread on Java 25. + +It answers the interview questions students most often get wrong: + +- "What is a virtual thread? How is it different from a platform thread?" +- "Do virtual threads make my application faster?" +- "What happens to the connection pool when you switch to virtual threads?" +- "Should you pool virtual threads? How do you limit concurrency then?" +- "What is pinning? Does `synchronized` still pin?" +- "Virtual threads or WebFlux?" + +## Tech Stack + +- **Java 25**, **Spring Boot 4** (Spring MVC on Tomcat), Spring JDBC, HikariCP +- **PostgreSQL 17** in Docker +- JUnit 5, AssertJ, Testcontainers, JFR (JDK Flight Recorder, in-process) + +## 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 5457 +./demo # 200 searches, at most 20 in flight +./check # 17 of 25 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 many requests at it at the same moment, and prints how many were +in flight at once, which threads served them, what the airline and the connection pool saw, and +ends with a `RESULT:` line. Every run starts a fresh application. + +``` +./demo 200 searches at GET /api/fares (scenario: search) +./demo --virtual on virtual threads on (or off) for this run only +./demo --requests 500 how many requests to send at the same moment +./demo --airline-ms 1000 how long the airline takes to answer (default 500) +./demo --pool-size 200 database connections, for this run only +./demo --scenario cpu CPU-bound requests, on platform and then on virtual threads +./demo --scenario pooled the airline calls handed to a thread pool (exhibit) +./demo --scenario pinning what pins a virtual thread on this JVM (no database needed) +./demo --help +``` + +### `./inspect` — look at the threads + +Starts the application, sends 50 slow searches, and while they all wait it takes a snapshot: the +executor Tomcat uses, the threads holding the requests (as `Thread.toString()` prints them, carrier +included), how many are mounted on a carrier right now, HikariCP's active and waiting counts, what +Postgres sees in `pg_stat_activity`, and which thread runs an `@Async` method. It records JFR's +`jdk.VirtualThreadPinned` events the whole time and ends with a pinning report. + +``` +./inspect 50 searches, settings from application.properties +./inspect --virtual off the same with platform threads +./inspect --requests 200 +``` + +### `./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 (`*Test` are plain unit tests, `*IT` start +the application against Postgres in Testcontainers). + +The tests never measure time. They hold the slow call at a gate and count: how many requests are in +flight, how many wait in Tomcat's queue, how many connections are held, how many callers are inside +the airline at once, which thread made the call, and what JFR recorded. + +The tests are the acceptance criteria. **Never edit, delete or disable a test.** + +## The code + +``` +start/src/main/ +├── resources/ +│ └── application.properties Tomcat 20 threads, pool 20, the airline. THE TASK 2 PROPERTY IS HERE +└── java/com/amigoscode/virtualthreads/ + ├── fares/ + │ ├── FareController.java GET /api/fares?route=LHR-JFK (slow) and GET /api/routes (fast) + │ ├── FareService.java route, airline, currency, save. THE BUGS OF TASKS 4 AND 5 ARE HERE + │ └── ...Repository.java plain JdbcTemplate + ├── money/ + │ ├── ExchangeRates.java converts the price. THE BUG OF TASK 7 IS HERE + │ └── RateTable.java 650 KB of exchange rates; counts how often it is built + ├── airline/ the HTTP client, and a fake airline: answers in 500 ms, allows 50 calls at once + ├── cpu/ GET /api/cpu: pure computation, for ./demo --scenario cpu + ├── exhibit/ PooledFareController: the thread-pool way to limit calls. Do not fix + ├── pinning/ PinningLab, for ./demo --scenario pinning + ├── threads/ InFlightRequests and ServerThreads: what the tools and tests measure + └── demo/ the demo and inspect tools. Nothing to change here +``` + +| Endpoint | What it does | +|---|---| +| `GET /api/fares?route=LHR-JFK¤cy=GBP` | Looks up the route, asks the airline (500 ms), converts the price, saves the search | +| `GET /api/routes` | Lists the routes. One small query, a few milliseconds | +| `GET /api/cpu?rounds=500000` | Hashes a value over and over. No waiting at all | +| `GET /api/fares/pooled?route=LHR-JFK` | The exhibit: the airline call goes through a fixed thread pool | + +## 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 thread-per-request ceiling | `./check 1` (passes: it documents the ceiling) | +| 2 | Turn on virtual threads | `./check 2` | +| 3 | Inspect virtual threads: carriers, unmounting, CPU-bound work | you answer questions (`./check 3` passes) | +| 4 | Fix the new bottleneck: the connection pool | `./check 4` | +| 5 | Limit the airline calls with a `Semaphore`, not a thread pool | `./check 5` | +| 6 | Inspect the limits: the pool, Postgres, the thread-pool exhibit, `@Async` | you answer questions | +| 7 | Fix the `ThreadLocal` cache | `./check 7` | +| 8 | Inspect pinning on Java 25, and decide when virtual threads help | you answer questions (`./check 8` passes) | + +## Solution + +`solution/` is the same project with every task done: `cd solution && ./check` prints 25 of 25. + +`start/` and `solution/` use the same database. `schema.sql` runs on every start and the demo +empties the search table before each run, so switching between them is safe. + +To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`). + +

+Spoiler: the problems and the fixes + +**The ceiling (Task 1).** Tomcat serves each request on one platform thread from a pool (here 20, +200 by default). A platform thread is an OS thread: about 1 MB of stack reserved, and the OS +schedules it. While a request waits 500 ms for the airline, its thread does nothing and nobody else +can use it. The 21st request waits in Tomcat's queue, even a request that needs 3 ms. + +**Virtual threads (Task 2).** `spring.threads.virtual.enabled=true`. Tomcat starts a new virtual +thread for every request. A virtual thread is a Java object scheduled by the JVM; it runs **mounted** +on a carrier thread (a platform thread of a `ForkJoinPool`, one per CPU core by default). When it +blocks on I/O, a lock or a sleep, the JVM **unmounts** it and the carrier runs another one. Waiting +becomes cheap, so you can have one thread per request again, with no pool and no limit. It does not +make CPU-bound work faster: 10 cores still do 10 things at once. + +**The connection pool (Task 4).** `FareService.search` was `@Transactional`, so each search held a +connection for the whole airline call. With 20 threads and 20 connections that was invisible. With +200 virtual threads, 180 wait for a connection and fail after 2 seconds (`SQLTransientConnectionException`). +Fix: do not hold a connection while you wait for something else. Remove the transaction around the +slow call (or do the slow call first, then a short transaction for the writes). Raising the pool to +200 is not a fix: Postgres allows 100 connections here, and every connection costs Postgres memory. + +**The airline's limit (Task 5).** Without the thread pool, 200 calls hit an airline that allows 50. +Fix: a `Semaphore(50)` around the call, `acquire()` before, `release()` in `finally`. The 51st +request waits on its own virtual thread. Not `Executors.newFixedThreadPool(50)`: that brings back a +pool of platform threads, a hidden queue and a second thread per request. Do not pool virtual +threads; limit the resource. + +**The ThreadLocal cache (Task 7).** A `ThreadLocal` was built once per pooled thread and +reused for years. A virtual thread serves one request and is gone, so the 650 KB table was built for +every request. Fix: the table is read-only, so share one instance. Prefer `ScopedValue` (final in +Java 25) to pass request data down a call; it is not a cache. + +**Pinning (Task 8).** On Java 21 to 23 a virtual thread that blocked inside `synchronized` stayed +on its carrier (pinned). Since Java 24 (JEP 491) it does not. On Java 25 it still pins while it +blocks inside a class initializer (or waits for another thread to finish one) and while a native +frame is on its stack. JFR's `jdk.VirtualThreadPinned` event shows every case, with the reason. + +**When to use which.** + +| | Platform threads (a pool) | Virtual threads | WebFlux (reactive) | +|---|---|---|---| +| Code style | Plain blocking code | The same plain blocking code | Non-blocking, `Mono`/`Flux` everywhere | +| Requests waiting on I/O at once | The pool size (200 by default) | As many as memory allows | As many as memory allows | +| A slow call costs | A whole OS thread | A small heap object | A callback | +| CPU-bound work | Limited by cores | Limited by cores, no gain | Limited by cores, no gain | +| Debugging, stack traces, `ThreadLocal` | Normal | Normal (but do not cache in a `ThreadLocal`) | Hard: stack traces are the framework's | +| Limits on shared resources | The pool hides them | You must add them: pool, semaphore | You must add them | +| Use it when | Little I/O waiting, or older Java | Many blocking I/O calls, Java 21+ (25 for `synchronized`) | Already reactive, streaming, backpressure end to end | + +
diff --git a/java/concepts/junior-mid/18-virtual-threads/TASKS_GUIDED.md b/java/concepts/junior-mid/18-virtual-threads/TASKS_GUIDED.md new file mode 100644 index 0000000..130cd83 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/TASKS_GUIDED.md @@ -0,0 +1,797 @@ +# Guided Tasks — Virtual Threads + +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`. + +All output below was copied from real runs on a laptop with 10 CPU cores and Java 25. Times, thread +numbers and the number of carrier threads (one per core) will differ on your machine. The counts of +requests in flight, the answers and the `RESULT` lines should match. + +**Before you start** + +```bash +cd start +docker compose up -d +``` + +--- + +## Task 1: See the Thread-per-Request Ceiling + +No code in this task. You are collecting evidence. + +### Run it + +```bash +./demo +``` + +### What you should see + +``` +Scenario: search | 200 searches at GET /api/fares?route=LHR-JFK, all at the same moment +Virtual threads: OFF | Tomcat: ThreadPoolExecutor: a pool of at most 20 platform threads, then a queue +The airline answers in 500 ms and allows 50 calls at once | DB pool: 20 connections, 2000 ms timeout + +Requests in flight at once (peak): 20 +Requests waiting in Tomcat's queue (peak): 181 +Airline calls at once (peak): 20 +Served by: 20 platform threads (http-nio-auto-1-exec-1, http-nio-auto-1-exec-2 ... http-nio-auto-1-exec-20) +Carrier threads under them: none: a platform thread is an OS thread, it is not mounted on anything +Airline called from: 20 platform threads (http-nio-auto-1-exec-1, http-nio-auto-1-exec-2 ... http-nio-auto-1-exec-20) +Platform threads in the JVM (peak): 62 (45 before the requests) +DB connections in use (peak): 20 of 20 +Requests waiting for a DB connection (peak): 0 +Rate tables built during the run: 17 (10,757 KB) +Answers: 200 x 200 OK +A fast GET /api/routes sent during the load: answered after 5,097 ms +Time taken: 5,201 ms + +RESULT: QUEUED. 200 requests, at most 20 in flight. +``` + +Every search got an answer, so nothing looks broken. But only 20 were ever being worked on. The +other 180 (181 with the route list) sat in Tomcat's queue. 200 / 20 = 10 rounds of 500 ms = 5 +seconds. + +### What just happened + +Spring MVC on Tomcat is **thread-per-request**: Tomcat takes a thread from its pool, and that thread +runs your controller, your service and your repository, from the first line to the response. Open +`application.properties`: + +```properties +server.tomcat.threads.max=20 +``` + +The default is 200. It is 20 here so the limit shows with 200 requests instead of 2,000. + +Each request spends almost all of its 500 ms waiting for the airline. The thread waits with it. It is +a **platform thread**, a thin wrapper around an OS thread: the OS reserves about 1 MB of stack for +it, and the OS scheduler decides when it runs. While it waits for a socket it does nothing, and +nobody else can use it. + +### The fast request + +Look at the second-last line: `GET /api/routes` is one small query, a few milliseconds of work. It +took **5 seconds**, because it waited in the same queue as the searches. A slow dependency fills the +pool and every endpoint gets slow. That is the symptom in the story. + +### Why not 10,000 threads? + +You could set `threads.max=10000`. 10,000 OS threads means up to 10 GB of reserved stack, and an OS +scheduler switching between 10,000 threads that mostly do nothing. That is why the default is 200, +and why services built on blocking code needed many instances, or went reactive. + +### Check + +```bash +./check 1 +``` + +``` +Task 1: See the thread-per-request ceiling + [PASS] Platform threads: 30 slow searches, Tomcat has 20 threads: 20 are in flight, the other 10 wait in Tomcat's queue + [PASS] Platform threads: while all 20 threads wait for the airline, even a fast GET /api/routes waits in the same queue + 2 of 2 pass +``` + +These pass on purpose: they pin the ceiling down. They do not measure time. The airline in the tests +is a stub that holds every call at a gate until the test opens it, so the test can count exactly +what is in flight and what is queued. + +--- + +## Task 2: Turn On Virtual Threads + +### Before + +```bash +./check 2 +``` + +``` + [FAIL] Virtual threads: 50 slow searches are all in flight at the same moment. Tomcat's limit of 20 threads no longer applies + Only 20 of 50 searches were in flight; 30 waited in Tomcat's queue for a free thread. + [FAIL] Virtual threads: every request is served by a virtual thread + 5 of 5 requests were served by platform threads: [http-nio-auto-1-exec-14, http-nio-auto-1-exec-5, http-nio-auto-1-exec-6, http-nio-auto-1-exec-18, http-nio-auto-1-exec-12] + 0 of 3 pass +``` + +### The change + +In `application.properties`: + +```properties +spring.threads.virtual.enabled=true +``` + +That is the whole change. Leave `server.tomcat.threads.max=20` where it is. + +### After + +```bash +./demo +``` + +``` +Virtual threads: ON | Tomcat: VirtualThreadExecutor: a new virtual thread for every request, no limit + +Requests in flight at once (peak): 200 +Requests waiting in Tomcat's queue (peak): 0 +Airline calls at once (peak): 20 +Served by: 200 virtual threads (tomcat-handler-3, tomcat-handler-4 ... tomcat-handler-202) +Carrier threads under them: 10 (ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-2, ForkJoinPool-1-worker-3 ... ForkJoinPool-1-worker-10) +Airline called from: 80 virtual threads, the request's own thread +Platform threads in the JVM (peak): 44 (37 before the requests) +DB connections in use (peak): 20 of 20 +Requests waiting for a DB connection (peak): 181 +Rate tables built during the run: 80 (50,625 KB) +Answers: 80 x 200 OK, 120 x 503 DB_POOL_TIMEOUT + for example: 503 HikariPool-1 - Connection is not available, request timed out after 2010ms (total=20, active=20, idle=0, waiti... +A fast GET /api/routes sent during the load: answered after 2,019 ms +Time taken: 2,594 ms + +RESULT: POOL EXHAUSTED. 120 of 200 searches failed: no database connection within 2000 ms (pool of 20). +``` + +The ceiling is gone: **200 in flight**, nothing in Tomcat's queue, 200 different virtual threads +named `tomcat-handler-N`, on 10 carrier threads. Tomcat's `threads.max` no longer applies: with +virtual threads Tomcat does not use a pool at all. + +And 120 searches failed. Keep that for Task 4. First, understand what you turned on. + +```bash +./check 2 +``` + +``` + [PASS] Virtual threads: the 50 request threads run on a few carrier threads, platform threads of a ForkJoinPool, fewer than 50 + [PASS] Virtual threads: 50 slow searches are all in flight at the same moment. Tomcat's limit of 20 threads no longer applies + [PASS] Virtual threads: every request is served by a virtual thread + 3 of 3 pass +``` + +--- + +## Task 3: Inspect Virtual Threads + +### Step 1 and 2: a blocked virtual thread has no carrier + +```bash +./inspect +``` + +``` +WHILE 50 SEARCHES WAIT (a snapshot) + Requests in flight 50 + Requests waiting in Tomcat's queue 0 + Threads holding them 50 virtual, 0 platform + Virtual threads mounted on a carrier now 0 of 50 + Carriers they started on 9 (ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-2 ... ForkJoinPool-1-worker-10) + Platform threads in the whole JVM 46 + + Three of the request threads, as Thread.toString() prints them: + VirtualThread[#273,tomcat-handler-8]/waiting + VirtualThread[#274,tomcat-handler-9]/timed_waiting + VirtualThread[#275,tomcat-handler-10]/timed_waiting +``` + +A running virtual thread prints its carrier after an `@`: +`VirtualThread[#52,tomcat-handler-0]/runnable@ForkJoinPool-1-worker-3`. These three print `waiting` +and no `@`: they are not on any carrier. **0 of 50 are mounted.** 50 requests are in progress and +not one carrier thread is busy with them. + +### What a virtual thread is + +- A virtual thread is a `java.lang.Thread`, but it is an object on the heap, scheduled by the JVM, + not by the OS. Creating one costs about as much as creating a small object. +- To run, it is **mounted** on a **carrier thread**: a platform thread of a `ForkJoinPool` that the + JVM keeps for this. By default there is one carrier per CPU core. +- When the code blocks (a socket read, `Thread.sleep`, a `ReentrantLock`, a `BlockingQueue`, and on + Java 24+ `synchronized`), the JVM copies the virtual thread's stack to the heap and **unmounts** it. + The carrier is free and runs another virtual thread. +- When the answer arrives, the virtual thread is scheduled again and mounted, maybe on another + carrier, and carries on from the same line. + +So "blocking" stops being expensive. A request waiting for the airline costs a few KB of heap, not an +OS thread. You keep the simple one-thread-per-request code, with no pool to size. + +The stack of a waiting request shows it, in `./inspect`: + +``` + Where the first one is waiting (top of its stack): + java.lang.VirtualThread.park + java.lang.System$1.parkVirtualThread + java.util.concurrent.locks.LockSupport.park + java.util.concurrent.CompletableFuture$Signaller.block + com.amigoscode.virtualthreads.airline.HttpAirlineClient.quote +``` + +`VirtualThread.park`: unmounted, waiting for the airline's answer. The code above it is ordinary +blocking code. Nothing in `HttpAirlineClient` knows about virtual threads. + +### Step 3 and 4: carriers and platform threads + +The carriers are named `ForkJoinPool-1-worker-N`, and there are 10 of them: one per core. Compare +with platform threads: + +```bash +./inspect --virtual off +``` + +``` +WHILE 50 SEARCHES WAIT (a snapshot) + Requests in flight 20 + Requests waiting in Tomcat's queue 30 + Threads holding them 0 virtual, 20 platform + Platform threads in the whole JVM 63 +``` + +20 platform threads, each holding one request. With virtual threads: 50 requests, and 46 platform +threads in the whole JVM (the carriers, Tomcat's acceptor and poller, HikariCP, JFR, Maven). + +### Step 5: CPU-bound work + +```bash +./demo --scenario cpu +``` + +``` +Scenario: cpu | 200 requests at GET /api/cpu, all at the same moment | 10 CPU cores +Each request hashes a value 500,000 times: pure computation, no waiting. + + Platform threads Virtual threads + In flight at once (peak) 20 10 + Answers 200 x 200 OK 200 x 200 OK + Time taken 1,023 ms 958 ms + +RESULT: NO GAIN. CPU-bound work took 1,023 ms on platform threads and 958 ms on virtual threads: both are limited by 10 CPU cores. +``` + +The same time (run it twice: the order flips). 10 cores do 10 things at once, whatever you call the +threads. And look at "In flight": only **10** on virtual threads. A virtual thread that never blocks +never unmounts. It keeps its carrier until it is done. Virtual threads help when threads **wait**. + +### Step 6: the tests + +```bash +./check 3 +``` + +``` + [PASS] Unmount: 1,000 virtual threads are blocked at the same moment, and not one of them is holding a carrier thread + [PASS] Carriers: those 1,000 virtual threads ran on a handful of carrier threads (about one per CPU core), not on 1,000 OS threads + 2 of 2 pass +``` + +### What to take away + +- Virtual threads do not make a request faster. They make waiting cheap, so many more requests can + wait at the same time. +- One carrier per core by default. A blocked virtual thread is unmounted and holds no carrier. +- CPU-bound work gains nothing. + +--- + +## Task 4: Fix the New Bottleneck: the Connection Pool + +### Step 1: what failed + +From Task 2: `120 x 503 DB_POOL_TIMEOUT`, and `Requests waiting for a DB connection (peak): 181`. +Even `GET /api/routes` took 2 seconds: it waited for a connection too. + +### Step 2: what the connections are doing + +`./inspect` again, a few lines further down: + +``` + HikariCP connections active 20, idle 0, requests waiting for one 30 + Postgres sessions of this app, by state idle in transaction: 20 +``` + +Postgres sees 20 sessions **idle in transaction**: a transaction is open and the database is waiting +for the next statement. Nothing is running in the database. The connections are held by requests +that are waiting for the **airline**. + +Open `FareService.search`: + +```java +@Transactional +public FareQuote search(String routeCode, String currency) { + Route route = routes.find(routeCode)...; // the transaction takes a connection here + AirlineQuote quote = askAirline(route.code()); // 500 ms, connection still held + ... + searches.save(fare); // INSERT + return fare; +} // commit: the connection goes back +``` + +A `@Transactional` method takes a connection when the transaction starts and gives it back at commit. +So every search held one for 500 ms. With 20 Tomcat threads and 20 connections, at most 20 requests +could ask, so nobody ever waited. The thread pool was protecting the connection pool. Virtual +threads removed that protection: 200 requests ask for 20 connections, 180 wait, and after 2 seconds +(`spring.datasource.hikari.connection-timeout=2000`) HikariCP gives up with +`SQLTransientConnectionException`. + +### Step 3: the obvious fix + +```bash +./demo --pool-size 200 --airline-ms 3000 +``` + +``` +Airline calls at once (peak): 59 +DB connections in use (peak): 100 of 200 +Requests waiting for a DB connection (peak): 101 +Answers: 50 x 200 OK, 150 x 503 AIRLINE_BUSY +RESULT: AIRLINE OVERLOADED. 150 of 200 searches were refused by the airline with 429: it allows 50 calls at once, it got 59. +``` + +The pool asked for 200 connections and got **100**: Postgres refused the rest +(`./inspect` prints `Postgres max_connections 100`). And with more requests getting through, the next +limit appeared: the airline. A bigger pool is not the fix: + +- `max_connections` is shared by every instance of your service. 4 instances x 200 = 800. +- Each Postgres connection is a process with its own memory. Hundreds of active connections make + the database slower, not faster. +- The connections were not doing anything. The problem is holding them, not having too few. + +### The fix + +Delete the `@Transactional` annotation from `search`, and its import +(`org.springframework.transaction.annotation.Transactional`). Change nothing else. + +Without a transaction, `routes.find` borrows a connection, runs the SELECT, and gives it straight +back. The airline call holds nothing. `searches.save` borrows one for the INSERT. + +Does this search need a transaction? It has one write. If it had several writes that must succeed +or fail together, you would do the slow call **first**, then call a short `@Transactional` method on +another bean for the writes. The rule: never hold a transaction (and its connection, and its locks) +across a call to something slow. + +### After + +```bash +./inspect +``` + +``` + HikariCP connections active 0, idle 20, requests waiting for one 0 + Postgres sessions of this app, by state idle: 20 +``` + +50 searches waiting for the airline, **0 connections held**. + +```bash +./demo +``` + +``` +Requests in flight at once (peak): 124 +Airline calls at once (peak): 57 +DB connections in use (peak): 20 of 20 +Requests waiting for a DB connection (peak): 30 +Answers: 50 x 200 OK, 150 x 503 AIRLINE_BUSY + for example: 503 The airline answered 429 Too Many Requests for LHR-JFK +A fast GET /api/routes sent during the load: answered after 23 ms +Time taken: 562 ms + +RESULT: AIRLINE OVERLOADED. 150 of 200 searches were refused by the airline with 429: it allows 50 calls at once, it got 57. +``` + +No more `DB_POOL_TIMEOUT`, and the route list is fast again (23 ms). Some requests still wait for a +connection for a moment (30 at the peak), but only for a few milliseconds each. The next limit is +the airline. That is Task 5. + +```bash +./check 4 +``` + +``` + [PASS] Pool: while 30 searches wait for the airline, none of them is holding a database connection + [PASS] Pool: 30 searches at the same moment, a pool of 10 connections: every search gets a fare, none times out waiting for a connection + [PASS] Pool: every search is still saved, with its price and the thread that served it + 3 of 3 pass +``` + +--- + +## Task 5: Limit the Airline Calls, Not the Threads + +**The idea:** the airline allows 50 calls at once. Before, Tomcat's 20 threads kept you under it by +accident. Now you need a limit on purpose, on the airline call only, so everything else stays +unlimited. + +### Before + +`./check 5`: 2 of 4 pass. + +``` + [FAIL] Airline limit: all 15 get a fare. A search over the limit waits for a free slot instead of failing + [failed searches] + Expecting empty but was: "10 of 15 searches failed, for example: 503 {"code":"AIRLINE_BUSY","message":"The airline answered 429 Too Many Requests: 9 calls were in progress, it allows 5"}" + [FAIL] Airline limit: 15 searches at once, the airline allows 5: it never has more than 5 calls in progress + The airline had 15 calls in progress at the same moment. It allows 5. +``` + +### The change + +In `FareService`, replace the `int maxAirlineCalls` field with a `Semaphore`: + +```java +private final Semaphore airlineCalls; +``` + +In the constructor, replace `this.maxAirlineCalls = maxAirlineCalls;` with: + +```java +this.airlineCalls = new Semaphore(maxAirlineCalls); +``` + +And replace `askAirline`: + +```java +private AirlineQuote askAirline(String route) { + try { + airlineCalls.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted while waiting for a free airline call", e); + } + try { + return airline.quote(route); + } finally { + airlineCalls.release(); + } +} +``` + +Imports: `java.util.concurrent.Semaphore` and +`com.amigoscode.virtualthreads.airline.AirlineUnavailableException`. + +- `acquire()` takes one of the 50 permits, or **waits** until one is free. On a virtual thread that + wait unmounts it: the 51st request costs nothing while it waits its turn. +- `release()` is in `finally`. If `quote` throws and the permit is not given back, the limit shrinks + by one for ever. After 50 failures nobody can call the airline again. +- The call still runs on the request's own thread. Nothing is handed anywhere. + +`tryAcquire()` (no waiting) would answer "busy" instead of waiting. `tryAcquire(5, SECONDS)` is a +good production choice: wait, but not for ever. + +### After + +```bash +./demo +``` + +``` +Requests in flight at once (peak): 200 +Airline calls at once (peak): 50 +Served by: 200 virtual threads (tomcat-handler-3, tomcat-handler-4 ... tomcat-handler-202) +Airline called from: 200 virtual threads, the request's own thread +Platform threads in the JVM (peak): 44 (37 before the requests) +Rate tables built during the run: 200 (126,562 KB) +Answers: 200 x 200 OK +A fast GET /api/routes sent during the load: answered after 32 ms +Time taken: 2,138 ms + +RESULT: OK. 200 requests in flight at once on 10 carrier threads, at most 50 at the airline. +``` + +All 200 in flight, exactly 50 at the airline, 2.1 seconds instead of 5.2 in Task 1, and the route +list answers in 32 ms during the load. + +```bash +./check 5 +``` + +4 of 4 pass. + +--- + +## Task 6: Inspect the Limits + +### Step 1: the pool now + +From Task 4: `active 0, idle 20` while 50 searches wait. 20 connections served all 200 searches, +because each one is held for a few milliseconds. Pool size is about how long you hold a connection, +not how many requests you have. HikariCP's own guidance is a small pool, about twice the number of +the database's CPU cores, not the number of threads. + +### Step 2: why not 200 connections + +You saw it: Postgres stopped at 100 (`max_connections`), and that limit is shared by every instance +of the service and every other client. Each connection is a Postgres process with its own memory, +and more active queries than database cores just queue inside Postgres instead of in your pool. + +### Step 3: the thread-pool way + +```bash +./demo --scenario pooled +``` + +``` +Requests in flight at once (peak): 200 +Airline calls at once (peak): 50 +Served by: 200 virtual threads (tomcat-handler-3, tomcat-handler-4 ... tomcat-handler-202) +Airline called from: 50 platform threads (airline-pool-1, airline-pool-2 ... airline-pool-50) +Platform threads in the JVM (peak): 94 (38 before the requests) +Answers: 200 x 200 OK + +RESULT: POOLED. 200 requests in flight at once, but every airline call was handed to one of 50 pooled platform threads. +``` + +`PooledFareController` hands each call to `Executors.newFixedThreadPool(50)` and waits on the +`Future`. It also limits the airline to 50. What it brings back: + +- **50 more platform threads** (94 at the peak instead of 44), sized by hand. +- **A hidden unbounded queue** in front of the pool. Nothing tells you how long it is. +- **Two threads per request.** The request's virtual thread is parked on `Future.get()` while a pool + thread makes the call. Anything the request thread carries in a `ThreadLocal` (a trace id in the + logging MDC, the security context, the current transaction) is not on the pool thread. + +That is the rule: **do not pool virtual threads**. A pool exists to reuse expensive threads and to +cap concurrency. Virtual threads are not expensive, so cap the resource instead, with a `Semaphore` +or the resource's own pool (HikariCP is the semaphore for connections). `./check 5` has a test for +it: with the thread pool, "called on the request's own virtual thread" fails. + +### Step 4: `@Async` + +`./inspect` and `./inspect --virtual off`, the SETTINGS block and the last lines: + +``` + @Async and applicationTaskExecutor SimpleAsyncTaskExecutor: a new virtual thread for every task, no limit + An @Async method ran on VirtualThread[#811,task-2]/runnable@ForkJoinPool-1-worker-6 + + @Async and applicationTaskExecutor ThreadPoolTaskExecutor: a pool of 8 platform threads, unbounded queue + An @Async method ran on Thread[#747,task-1,5,com.amigoscode.virtualthreads.demo.Inspect] +``` + +`spring.threads.virtual.enabled=true` changes more than Tomcat: Spring Boot's `applicationTaskExecutor` +(used by `@Async`) becomes a `SimpleAsyncTaskExecutor` that starts a virtual thread per task, and has +**no limit**. Before, it was 8 threads and a queue. If an `@Async` method calls something scarce, +set `spring.task.execution.simple.concurrency-limit` or put a `Semaphore` around the call. + +### Step 5: where the time goes + +`./demo --virtual off`: `Time taken: 5,244 ms` and `RESULT: QUEUED`. With virtual threads: +2,138 ms. 200 searches / 50 airline calls at once = 4 rounds of 500 ms = 2 seconds. The airline is +now the limit, and it should be: it is the real one. + +### What to take away + +The pool of 20 platform threads was limiting four things at once without anybody deciding it: the +requests, the connections, the airline calls and the number of rate tables. Virtual threads remove +the accidental limit. Every scarce resource needs its own, explicit one. + +--- + +## Task 7: Fix the ThreadLocal Cache + +### Before + +Look at one line of the `./demo` output you already have, with and without virtual threads: + +``` +Rate tables built during the run: 200 (126,562 KB) (virtual threads) +Rate tables built during the run: 17 (10,757 KB) (./demo --virtual off) +``` + +Open `ExchangeRates`: + +```java +private static final ThreadLocal TABLE = ThreadLocal.withInitial(RateTable::build); +``` + +A `ThreadLocal` gives each thread its own copy. With a pool of 20 reused threads that means at most +20 tables, built once and used for years. A virtual thread serves one request and ends, so every +request builds a 650 KB table, uses it once and throws it away: 124 MB of garbage for 200 searches. +With a million virtual threads it is not only garbage: each live thread holds its own copy. + +``` + [FAIL] ThreadLocal: 20 searches on virtual threads build the rate table at most once, not once per request + 20 searches built the rate table 20 times (12,656 KB). Each virtual thread serves one request, so a ThreadLocal is never reused. +``` + +### The change + +Why was it a `ThreadLocal` at all? Usually because the object is not thread-safe (like +`SimpleDateFormat`) or someone assumed it was not. Open `RateTable`: every field is `final` and +nothing writes to the array after the constructor. It is read-only, so one table can be shared by +every thread. In `ExchangeRates`: + +```java +private final RateTable table = RateTable.build(); + +public BigDecimal fromUsd(long usdCents, String currency) { + return table.fromUsd(usdCents, currency); +} +``` + +If the object really is not thread-safe: make it immutable (`DateTimeFormatter` instead of +`SimpleDateFormat`), create it per use if it is cheap, or keep a small bounded pool of the objects, +not of threads. + +### After + +``` +Rate tables built during the run: 0 (0 KB) +RESULT: OK. 200 requests in flight at once on 10 carrier threads, at most 50 at the airline. +``` + +`./check 7`: 3 of 3 pass. + +### `ThreadLocal` and `ScopedValue` + +A `ThreadLocal` still works on virtual threads. Using one to **pass request data** down a call (the +current user, a trace id) is fine. Using one as a **cache** is the mistake. For passing data, Java 25 +has `ScopedValue` (JEP 506, final in Java 25: no `--enable-preview`): + +```java +static final ScopedValue CUSTOMER = ScopedValue.newInstance(); + +ScopedValue.where(CUSTOMER, "alice").run(() -> service.search(...)); // CUSTOMER.get() inside +``` + +It is immutable, it ends with the `run`, and it cannot leak into the next task. (Structured +concurrency, `StructuredTaskScope`, is still a preview in Java 25.) + +--- + +## Task 8: Inspect Pinning, and Decide + +### Step 1: what pins on Java 25 + +```bash +./demo --scenario pinning +``` + +``` +Scenario: pinning | Java 25+36-LTS | 20 virtual threads per case, each blocks for 100 ms | 10 CPU cores, so 10 carrier threads +Pinned: the virtual thread could not unmount while it was blocked, so it held on to its carrier thread. +Every pinned block is recorded with JFR (event jdk.VirtualThreadPinned), in this JVM. + + Case Pinned Time Why, as JFR reports it + -------------------------------------------- ------ ------- ---------------------- + synchronized, Thread.sleep inside 0 108 ms + synchronized, Object.wait inside 0 106 ms + ReentrantLock, Thread.sleep inside 0 110 ms + Thread.sleep inside a static initializer 10 110 ms VM call to SlowStaticInit. on stack + Waited for initialization of SlowStaticInit by another thread + Thread.sleep in a callback from native code 20 220 ms Native or VM frame on stack + +RESULT: synchronized does NOT pin on Java 25 (JEP 491). Still pinned: blocking inside a static initializer; blocking in a callback from native code. +``` + +**Pinning** means a virtual thread blocks but cannot unmount, so it keeps its carrier busy. With +one carrier per core, 10 pinned threads stop every other virtual thread in the JVM. + +- **`synchronized`: 0.** On Java 21 to 23 a virtual thread that blocked inside `synchronized` was + pinned, which is why so much advice says "replace `synchronized` with `ReentrantLock`". Java 24 + (JEP 491) changed the JVM's monitors so it can unmount. We ran the same check on Java 21: one pinned + event for one thread sleeping inside `synchronized`. On Java 25: none. `Object.wait()` does not pin + either. +- **Static initializer: still pins.** 20 threads touched the same class. One ran its slow static + initializer, pinned. The others waited for it to finish, also pinned. JFR saw 10, one per carrier: + **every carrier was blocked**, and the other 10 virtual threads could not even start until the + initializer was done. +- **Native callback: still pins.** The case calls C's `qsort` through the Foreign Function API, and + `qsort` calls back into Java, which sleeps. The JVM cannot move a native frame to the heap, so the + thread stays mounted. 20 threads on 10 carriers ran in two rounds: 220 ms instead of 110. + +(On Windows, if `qsort` cannot be found, the native case says "skipped".) + +### Step 3 and 4: the tests + +```bash +./check 8 +``` + +``` + [PASS] Java 25: Object.wait() inside synchronized does not pin either + [PASS] Java 25: a virtual thread that blocks inside synchronized is not pinned (JEP 491, since Java 24) + [PASS] Java 25: a virtual thread that blocks inside a static initializer is still pinned + 3 of 3 pass +``` + +They do not measure time. They start a JFR `RecordingStream` in the test's own JVM, block a virtual +thread on a latch in each way, and count the `jdk.VirtualThreadPinned` events. + +### Step 5: pinning in the real application + +The PINNING section of `./inspect`, in Task 3 (before the pool fix): + +``` +PINNING (JFR event jdk.VirtualThreadPinned, recorded during this run) + 80 pinned blocks: + 13 x Freeze or preempt failed (2) | at com.zaxxer.hikari.pool.HikariPool.createTimeoutException + 6 x Waited for initialization of java.sql.SQLTransientConnectionException by another thread | at com.zaxxer.hikari.pool.HikariPool.createTimeoutException + 29 x Freeze or preempt failed (2) | at org.codehaus.mojo.exec.URLClassLoaderBuilder$ExecJavaClassLoader.loadClass + ... +``` + +And after all the fixes (some runs show none at all): + +``` + 6 pinned blocks: + 6 x Waited for initialization of java.util.concurrent.LinkedTransferQueue$DualNode by another thread | at com.zaxxer.hikari.util.ConcurrentBag.borrow +``` + +All of them happened the first time a class was loaded or initialized: 30 requests timed out at +the same moment and all needed `SQLTransientConnectionException`, used for the first time in that +JVM. ("Freeze or preempt failed" is the JVM saying it could not unmount the thread at that point, +here while a class was being loaded.) It happens once per class per JVM: the second time the same +code runs, it is gone. Pinning to worry about is pinning that repeats on every request. + +### Step 6: how to find it on Java 25 + +`-Djdk.tracePinnedThreads` was removed in Java 24: on Java 25 the flag does nothing. Use JFR: + +```bash +java -XX:StartFlightRecording:filename=app.jfr,settings=profile -jar app.jar +jfr print --events jdk.VirtualThreadPinned app.jfr +``` + +The event has the stack trace and, since Java 24, a `pinnedReason`. + +### Step 7: decide + +**Virtual threads help** when requests spend their time **waiting**: HTTP calls to other services, +JDBC, a message broker. Many waiting requests, written as plain blocking code. + +**They do not help** with CPU-bound work, and they do not make a slow dependency faster: the airline +still takes 500 ms. They also do not remove limits; they move them to the pool, the database and the +partner API, where you must add them on purpose. + +**Compared with WebFlux.** Both let a few OS threads serve thousands of waiting requests. WebFlux +gets there by never blocking: `Mono` and `Flux` everywhere, reactive drivers (R2DBC instead of JDBC), +and stack traces that show the framework instead of your code. Virtual threads get there with the +code you already write. Choose WebFlux when you need streaming and backpressure end to end, or the +code is already reactive. For a typical Spring MVC service on Java 21+, turn on virtual threads. + +### How to say it in an interview + +> "A virtual thread is a Java thread scheduled by the JVM instead of the OS. It runs on a small pool +> of carrier threads, one per core, and when it blocks on I/O the JVM unmounts it, so the carrier +> can run someone else. That makes blocking cheap, so we keep simple thread-per-request code without +> a 200-thread limit. In Spring Boot it is one property, `spring.threads.virtual.enabled`. It does +> not make anything faster, and CPU-bound work gains nothing. What changes is that the thread pool no +> longer limits concurrency, so the limits move to the real resources: I would make sure nothing +> holds a database connection across a slow call, put a semaphore around rate-limited dependencies +> instead of a thread pool, and never use a ThreadLocal as a cache. On Java 25, `synchronized` no +> longer pins; class initializers and native frames still do, and JFR's `jdk.VirtualThreadPinned` +> event shows where." + +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/18-virtual-threads/solution/.mvn/jvm.config b/java/concepts/junior-mid/18-virtual-threads/solution/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/18-virtual-threads/solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/solution/check b/java/concepts/junior-mid/18-virtual-threads/solution/check new file mode 100755 index 0000000..be8b918 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/check.cmd b/java/concepts/junior-mid/18-virtual-threads/solution/check.cmd new file mode 100644 index 0000000..169aada --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/compose.yaml b/java/concepts/junior-mid/18-virtual-threads/solution/compose.yaml new file mode 100644 index 0000000..6ee7af3 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/compose.yaml @@ -0,0 +1,16 @@ +name: virtual-threads +services: + postgres: + image: postgres:17-alpine + container_name: virtual-threads-postgres + environment: + POSTGRES_DB: fares + POSTGRES_USER: fares + POSTGRES_PASSWORD: fares + ports: + - "5457:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U fares -d fares"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/demo b/java/concepts/junior-mid/18-virtual-threads/solution/demo new file mode 100755 index 0000000..ed936b4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/demo.cmd b/java/concepts/junior-mid/18-virtual-threads/solution/demo.cmd new file mode 100644 index 0000000..5441daf --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/inspect b/java/concepts/junior-mid/18-virtual-threads/solution/inspect new file mode 100755 index 0000000..2ca5934 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/inspect.cmd b/java/concepts/junior-mid/18-virtual-threads/solution/inspect.cmd new file mode 100644 index 0000000..cf8de79 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/mvnw b/java/concepts/junior-mid/18-virtual-threads/solution/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/solution/mvnw.cmd b/java/concepts/junior-mid/18-virtual-threads/solution/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/solution/pom.xml b/java/concepts/junior-mid/18-virtual-threads/solution/pom.xml new file mode 100644 index 0000000..171571d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + virtual-threads + 0.0.1-SNAPSHOT + virtual-threads + Virtual threads: watch the thread-per-request ceiling, lift it, then find the limits that are left + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-jdbc + + + 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.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/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java new file mode 100644 index 0000000..63133bc --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java @@ -0,0 +1,68 @@ +package com.amigoscode.virtualthreads; + +import com.amigoscode.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.fares.UnknownRouteException; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import java.sql.SQLTransientConnectionException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** Turns the failures a fare search can run into into clear JSON errors. Nothing to change here. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(UnknownRouteException.class) + public ResponseEntity unknownRoute(UnknownRouteException e) { + return error(HttpStatus.NOT_FOUND, "UNKNOWN_ROUTE", e.getMessage()); + } + + @ExceptionHandler(UnknownCurrencyException.class) + public ResponseEntity unknownCurrency(UnknownCurrencyException e) { + return error(HttpStatus.BAD_REQUEST, "UNKNOWN_CURRENCY", e.getMessage()); + } + + /** The airline refused the call: too many calls were in progress at once. */ + @ExceptionHandler(AirlineBusyException.class) + public ResponseEntity airlineBusy(AirlineBusyException e) { + return error(HttpStatus.SERVICE_UNAVAILABLE, "AIRLINE_BUSY", e.getMessage()); + } + + @ExceptionHandler(AirlineUnavailableException.class) + public ResponseEntity airlineUnavailable(AirlineUnavailableException e) { + return error(HttpStatus.BAD_GATEWAY, "AIRLINE_ERROR", e.getMessage()); + } + + /** + * No database connection became free within spring.datasource.hikari.connection-timeout. + * Spring wraps HikariCP's SQLTransientConnectionException: in CannotCreateTransactionException + * when a @Transactional method starts, in CannotGetJdbcConnectionException for a plain query. + */ + @ExceptionHandler({CannotCreateTransactionException.class, DataAccessResourceFailureException.class}) + public ResponseEntity noConnection(RuntimeException e) { + Throwable cause = e; + while (cause != null && !(cause instanceof SQLTransientConnectionException)) { + cause = cause.getCause(); + } + if (cause == null) { + return error(HttpStatus.SERVICE_UNAVAILABLE, "DATABASE_ERROR", e.getMessage()); + } + String message = cause.getMessage(); + if (cause.getCause() != null && cause.getCause().getMessage() != null) { + // For example Postgres refusing a new connection: "FATAL: sorry, too many clients already". + message += " Caused by: " + cause.getCause().getMessage().lines().findFirst().orElse(""); + } + return error(HttpStatus.SERVICE_UNAVAILABLE, "DB_POOL_TIMEOUT", message); + } + + private static ResponseEntity error(HttpStatus status, String code, String message) { + return ResponseEntity.status(status).body(new ApiError(code, message)); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java new file mode 100644 index 0000000..cc3fb04 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.virtualthreads; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VirtualThreadsApplication { + + public static void main(String[] args) { + SpringApplication.run(VirtualThreadsApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java new file mode 100644 index 0000000..83735f6 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java @@ -0,0 +1,9 @@ +package com.amigoscode.virtualthreads.airline; + +/** The airline answered 429 Too Many Requests: too many calls were in progress at once. */ +public class AirlineBusyException extends RuntimeException { + + public AirlineBusyException(String message) { + super(message); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java new file mode 100644 index 0000000..9f33998 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java @@ -0,0 +1,10 @@ +package com.amigoscode.virtualthreads.airline; + +/** + * Asks an airline for the price of a route. A blocking call: the calling thread waits until the + * airline answers, which takes about half a second. + */ +public interface AirlineClient { + + AirlineQuote quote(String route); +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java new file mode 100644 index 0000000..eb77c24 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java @@ -0,0 +1,5 @@ +package com.amigoscode.virtualthreads.airline; + +/** What the airline answers: its name and the price in US cents. */ +public record AirlineQuote(String airline, long priceCents) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java new file mode 100644 index 0000000..2aaa2c2 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java @@ -0,0 +1,13 @@ +package com.amigoscode.virtualthreads.airline; + +/** The airline could not be reached, or answered with an error. */ +public class AirlineUnavailableException extends RuntimeException { + + public AirlineUnavailableException(String message) { + super(message); + } + + public AirlineUnavailableException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java new file mode 100644 index 0000000..960918e --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java @@ -0,0 +1,129 @@ +package com.amigoscode.virtualthreads.airline; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Stands in for the airline's API: a small HTTP server on its own port, started with the + * application. It answers GET /quote?route=LHR-JFK after airline.delay-ms, and, like a real partner + * API, it has a rate limit: when more than airline.max-concurrent-calls calls are in progress at + * once, it answers 429 Too Many Requests straight away. Nothing to change here. + */ +@Component +public class FakeAirline implements DisposableBean { + + private final long delayMillis; + private final int maxConcurrentCalls; + private final HttpServer server; + private final ExecutorService handlers = Executors.newVirtualThreadPerTaskExecutor(); + + private final AtomicInteger inProgress = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger answered = new AtomicInteger(); + private final AtomicInteger refused = new AtomicInteger(); + + public FakeAirline(@Value("${airline.delay-ms:500}") long delayMillis, + @Value("${airline.max-concurrent-calls:50}") int maxConcurrentCalls) throws IOException { + this.delayMillis = delayMillis; + this.maxConcurrentCalls = maxConcurrentCalls; + this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 1000); + server.createContext("/quote", this::quote); + server.setExecutor(handlers); + server.start(); + } + + public URI baseUri() { + return URI.create("http://127.0.0.1:" + server.getAddress().getPort()); + } + + public long delayMillis() { + return delayMillis; + } + + public int maxConcurrentCalls() { + return maxConcurrentCalls; + } + + /** Calls the airline is working on right now. */ + public int inProgress() { + return inProgress.get(); + } + + /** The most calls that were in progress at the same moment since the last reset. */ + public int peak() { + return peak.get(); + } + + public int answered() { + return answered.get(); + } + + /** Calls refused with 429 because too many were in progress. */ + public int refused() { + return refused.get(); + } + + public void resetCounters() { + peak.set(inProgress.get()); + answered.set(0); + refused.set(0); + } + + private void quote(HttpExchange exchange) throws IOException { + int now = inProgress.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + try { + if (now > maxConcurrentCalls) { + refused.incrementAndGet(); + send(exchange, 429, "{\"error\":\"too many calls in progress, the limit is " + maxConcurrentCalls + "\"}"); + return; + } + sleep(delayMillis); + String route = exchange.getRequestURI().getQuery() == null ? "" : exchange.getRequestURI().getQuery().replace("route=", ""); + answered.incrementAndGet(); + send(exchange, 200, "{\"airline\":\"Skyway\",\"priceCents\":" + priceCents(route) + "}"); + } finally { + inProgress.decrementAndGet(); + } + } + + /** A fixed price per route, between 99.00 and 698.99 dollars. */ + static long priceCents(String route) { + return 9_900 + Math.floorMod(route.hashCode(), 60_000); + } + + private static void send(HttpExchange exchange, int status, String json) throws IOException { + byte[] body = json.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void destroy() { + server.stop(0); + handlers.shutdownNow(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java new file mode 100644 index 0000000..370f472 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java @@ -0,0 +1,65 @@ +package com.amigoscode.virtualthreads.airline; + +import java.net.http.HttpClient; +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientException; + +/** + * Calls the airline over HTTP. {@code quote} blocks: the calling thread waits for the answer. On a + * platform thread that is an OS thread doing nothing for half a second. On a virtual thread the JVM + * unmounts it while it waits, and the carrier thread serves someone else. Nothing to change here. + */ +@Component +public class HttpAirlineClient implements AirlineClient { + + private final RestClient http; + private final Set callerThreads = ConcurrentHashMap.newKeySet(); + + public HttpAirlineClient(FakeAirline airline) { + HttpClient client = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)) + // The JDK client's own helper tasks run on virtual threads, so they do not add + // platform threads to what the demo counts. + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + JdkClientHttpRequestFactory requests = new JdkClientHttpRequestFactory(client); + requests.setReadTimeout(Duration.ofSeconds(30)); + this.http = RestClient.builder().baseUrl(airline.baseUri().toString()).requestFactory(requests).build(); + } + + @Override + public AirlineQuote quote(String route) { + Thread caller = Thread.currentThread(); + callerThreads.add((caller.isVirtual() ? "virtual " : "platform ") + caller.getName()); + try { + return http.get() + .uri("/quote?route={route}", route) + .retrieve() + .onStatus(status -> status.value() == HttpStatus.TOO_MANY_REQUESTS.value(), (request, response) -> { + throw new AirlineBusyException("The airline answered 429 Too Many Requests for " + route); + }) + .body(AirlineQuote.class); + } catch (AirlineBusyException e) { + throw e; + } catch (RestClientException e) { + throw new AirlineUnavailableException("The airline did not answer for " + route + ": " + e.getMessage(), e); + } + } + + /** "virtual tomcat-handler-12" or "platform airline-pool-3": one entry per thread that called the airline. */ + public Set callerThreads() { + return Set.copyOf(callerThreads); + } + + public void resetCallerThreads() { + callerThreads.clear(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java new file mode 100644 index 0000000..0b9e761 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java @@ -0,0 +1,48 @@ +package com.amigoscode.virtualthreads.cpu; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * CPU-bound work: hash a value over and over. No waiting at all, the thread computes the whole + * time. Used by ./demo --scenario cpu to show what virtual threads do NOT speed up. Nothing to + * change here. + */ +@RestController +public class CpuController { + + private final InFlightRequests inFlight; + + public CpuController(InFlightRequests inFlight) { + this.inFlight = inFlight; + } + + @GetMapping("/api/cpu") + public Map hash(@RequestParam(defaultValue = "100000") int rounds) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + byte[] value = "fare".getBytes(StandardCharsets.UTF_8); + MessageDigest sha256 = sha256(); + for (int i = 0; i < rounds; i++) { + value = sha256.digest(value); + } + Thread thread = Thread.currentThread(); + return Map.of("rounds", rounds, "hash", HexFormat.of().formatHex(value), + "servedBy", thread.getName(), "virtual", thread.isVirtual()); + } + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Db.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Db.java new file mode 100644 index 0000000..1897ef4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.virtualthreads.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:5457/fares"); + static final String USER = env("DB_USER", "fares"); + static final String PASSWORD = env("DB_PASSWORD", "fares"); + + 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/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java new file mode 100644 index 0000000..ef48c8d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java @@ -0,0 +1,415 @@ +package com.amigoscode.virtualthreads.demo; + +import static com.amigoscode.virtualthreads.demo.Tool.line; +import static com.amigoscode.virtualthreads.demo.Tool.n; + +import com.amigoscode.virtualthreads.airline.FakeAirline; +import com.amigoscode.virtualthreads.airline.HttpAirlineClient; +import com.amigoscode.virtualthreads.demo.Tool.Reply; +import com.amigoscode.virtualthreads.demo.Tool.Sampler; +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.pinning.PinningLab; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.net.http.HttpClient; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.IntSupplier; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Starts the real application, sends many requests at it at the same moment, and prints how many + * were in flight at once, which threads served them, and what ran out. Run it with ./demo (or + * .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final String ROUTE = "LHR-JFK"; + private static final ThreadMXBean THREADS = ManagementFactory.getThreadMXBean(); + + private record Options(String scenario, int requests, Boolean virtual, long airlineMillis, Integer poolSize) { + } + + 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; + } + switch (options.scenario()) { + case "pinning" -> pinning(); + case "cpu" -> { + if (Db.isUp()) { + cpu(options); + } + } + default -> { + if (Db.isUp()) { + searches(options); + } + } + } + } + + // ---------------------------------------------------------------- search and pooled + + private static void searches(Options options) throws Exception { + boolean pooled = options.scenario().equals("pooled"); + List springArgs = new ArrayList<>(List.of("--airline.delay-ms=" + options.airlineMillis())); + if (options.virtual() != null) { + springArgs.add("--spring.threads.virtual.enabled=" + options.virtual()); + } + if (options.poolSize() != null) { + springArgs.add("--spring.datasource.hikari.maximum-pool-size=" + options.poolSize()); + } + try (ConfigurableApplicationContext context = Tool.startApplication(springArgs); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + ServerThreads server = context.getBean(ServerThreads.class); + FakeAirline airline = context.getBean(FakeAirline.class); + HttpAirlineClient airlineClient = context.getBean(HttpAirlineClient.class); + HikariDataSource dataSource = Tool.hikari(context); + HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); + JdbcTemplate jdbc = context.getBean(JdbcTemplate.class); + String baseUrl = Tool.baseUrl(context); + HttpClient http = Tool.httpClient(); + String path = pooled ? "/api/fares/pooled?route=" + ROUTE : "/api/fares?route=" + ROUTE; + + // Fresh state for every run, and a few throwaway requests so startup work is not measured. + jdbc.execute("truncate table fare_search restart identity"); + for (int i = 0; i < 3; i++) { + Tool.send(http, Tool.get(baseUrl + path)); + } + inFlight.reset(); + airline.resetCounters(); + airlineClient.resetCallerThreads(); + int tablesBefore = RateTable.timesBuilt(); + int platformBefore = THREADS.getThreadCount(); + THREADS.resetPeakThreadCount(); + + System.out.println(); + System.out.println("Scenario: " + options.scenario() + " | " + n(options.requests()) + " searches at GET " + path + + ", all at the same moment"); + System.out.println("Virtual threads: " + (server.virtual() ? "ON" : "OFF") + " | Tomcat: " + server.describe()); + System.out.println("The airline answers in " + airline.delayMillis() + " ms and allows " + airline.maxConcurrentCalls() + + " calls at once | DB pool: " + dataSource.getMaximumPoolSize() + " connections, " + + dataSource.getConnectionTimeout() + " ms timeout"); + System.out.println(); + + Map gauges = new LinkedHashMap<>(); + gauges.put("queued", server::queued); + gauges.put("dbActive", pool::getActiveConnections); + gauges.put("dbWaiting", pool::getThreadsAwaitingConnection); + long startedAt = System.nanoTime(); + List replies; + long fastMillis; + try (Sampler sampler = new Sampler(gauges)) { + List> futures = Tool.fire(http, options.requests(), i -> Tool.get(baseUrl + path), senders); + Future fast = senders.submit(() -> { + Thread.sleep(100); + long sentAt = System.nanoTime(); + Tool.send(http, Tool.get(baseUrl + "/api/routes")); + return (System.nanoTime() - sentAt) / 1_000_000; + }); + replies = Tool.collect(futures); + fastMillis = fast.get(); + long millis = (System.nanoTime() - startedAt) / 1_000_000; + sampler.close(); + + List threadNames = new ArrayList<>(inFlight.threadNames()); + List carriers = new ArrayList<>(inFlight.carriers()); + int virtualServed = inFlight.servedByVirtualThreads(); + int platformServed = inFlight.servedByPlatformThreads(); + + line("Requests in flight at once (peak):", inFlight.peak()); + line("Requests waiting in Tomcat's queue (peak):", sampler.highest("queued")); + line("Airline calls at once (peak):", airline.peak()); + line("Served by:", servedBy(virtualServed, platformServed, threadNames)); + line("Carrier threads under them:", carriers.isEmpty() + ? "none: a platform thread is an OS thread, it is not mounted on anything" + : carriers.size() + " (" + Tool.some(carriers, 3) + ")"); + line("Airline called from:", calledFrom(airlineClient.callerThreads())); + line("Platform threads in the JVM (peak):", THREADS.getPeakThreadCount() + " (" + platformBefore + " before the requests)"); + line("DB connections in use (peak):", sampler.highest("dbActive") + " of " + dataSource.getMaximumPoolSize()); + line("Requests waiting for a DB connection (peak):", sampler.highest("dbWaiting")); + line("Rate tables built during the run:", (RateTable.timesBuilt() - tablesBefore) + + " (" + n((RateTable.timesBuilt() - tablesBefore) * RateTable.BYTES / 1024) + " KB)"); + line("Answers:", Tool.answers(replies)); + replies.stream().filter(reply -> reply.status() != 200).findFirst().ifPresent(reply -> + line(" for example:", reply.status() + " " + shorten(Tool.json(reply.body(), "message") == null + ? reply.body() : Tool.json(reply.body(), "message"), 110))); + line("A fast GET /api/routes sent during the load:", "answered after " + n(fastMillis) + " ms"); + line("Time taken:", n(millis) + " ms"); + System.out.println(); + printResult(options, pooled, replies, inFlight.peak(), carriers.size(), airline, airlineClient, dataSource); + } + } + System.out.println(); + } + + private static void printResult(Options options, boolean pooled, List replies, int peak, int carriers, + FakeAirline airline, HttpAirlineClient airlineClient, HikariDataSource dataSource) { + int total = replies.size(); + long poolTimeouts = replies.stream().filter(reply -> "DB_POOL_TIMEOUT".equals(reply.code())).count(); + long airlineBusy = replies.stream().filter(reply -> "AIRLINE_BUSY".equals(reply.code())).count(); + long otherErrors = replies.stream().filter(reply -> reply.status() != 200).count() - poolTimeouts - airlineBusy; + boolean failed = false; + if (poolTimeouts > 0) { + failed = true; + System.out.println("RESULT: POOL EXHAUSTED. " + poolTimeouts + " of " + total + + " searches failed: no database connection within " + dataSource.getConnectionTimeout() + + " ms (pool of " + dataSource.getMaximumPoolSize() + ")."); + } + if (airlineBusy > 0) { + failed = true; + System.out.println("RESULT: AIRLINE OVERLOADED. " + airlineBusy + " of " + total + + " searches were refused by the airline with 429: it allows " + airline.maxConcurrentCalls() + + " calls at once, it got " + airline.peak() + "."); + } + if (otherErrors > 0) { + failed = true; + System.out.println("RESULT: ERRORS. " + otherErrors + " of " + total + " searches failed."); + } + if (failed) { + return; + } + if (peak < total) { + System.out.println("RESULT: QUEUED. " + total + " requests, at most " + peak + " in flight."); + } else if (pooled) { + long platformCallers = airlineClient.callerThreads().stream().filter(name -> name.startsWith("platform ")).count(); + System.out.println("RESULT: POOLED. " + total + " requests in flight at once, but every airline call was handed to one of " + + platformCallers + " pooled platform threads."); + } else if (carriers == 0) { + System.out.println("RESULT: OK. " + total + " requests in flight at once, on " + total + + " platform threads, at most " + airline.peak() + " at the airline."); + } else { + System.out.println("RESULT: OK. " + total + " requests in flight at once on " + carriers + + " carrier threads, at most " + airline.peak() + " at the airline."); + } + } + + private static String servedBy(int virtual, int platform, List names) { + List parts = new ArrayList<>(); + if (platform > 0) { + List platformNames = names.stream().filter(name -> !name.startsWith("tomcat-handler")).toList(); + parts.add(platformNames.size() + " platform threads (" + Tool.some(platformNames, 2) + ")"); + } + if (virtual > 0) { + List virtualNames = names.stream().filter(name -> name.startsWith("tomcat-handler")).toList(); + parts.add(virtual + " virtual threads (" + Tool.some(virtualNames, 2) + ")"); + } + return String.join(" and ", parts); + } + + private static String calledFrom(java.util.Set callers) { + List virtual = callers.stream().filter(name -> name.startsWith("virtual ")).map(name -> name.substring(8)).toList(); + List platform = callers.stream().filter(name -> name.startsWith("platform ")).map(name -> name.substring(9)).toList(); + List parts = new ArrayList<>(); + if (!virtual.isEmpty()) { + parts.add(virtual.size() + " virtual threads, the request's own thread"); + } + if (!platform.isEmpty()) { + parts.add(platform.size() + " platform threads (" + Tool.some(platform, 2) + ")"); + } + return parts.isEmpty() ? "nobody" : String.join(" and ", parts); + } + + private static String shorten(String text, int max) { + String oneLine = text == null ? "" : text.replaceAll("\\s+", " "); + return oneLine.length() <= max ? oneLine : oneLine.substring(0, max) + "..."; + } + + // ---------------------------------------------------------------- cpu + + private static final int CPU_ROUNDS = 500_000; + + private static void cpu(Options options) throws Exception { + int cores = Runtime.getRuntime().availableProcessors(); + System.out.println(); + System.out.println("Scenario: cpu | " + n(options.requests()) + " requests at GET /api/cpu, all at the same moment | " + + cores + " CPU cores"); + System.out.println("Each request hashes a value " + n(CPU_ROUNDS) + " times: pure computation, no waiting."); + System.out.println("The application is started twice: once with platform threads, once with virtual threads."); + System.out.println(); + long[] millis = new long[2]; + int[] peaks = new int[2]; + String[] served = new String[2]; + for (int run = 0; run < 2; run++) { + boolean virtual = run == 1; + try (ConfigurableApplicationContext context = Tool.startApplication(List.of("--spring.threads.virtual.enabled=" + virtual)); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + String url = Tool.baseUrl(context) + "/api/cpu?rounds=" + CPU_ROUNDS; + HttpClient http = Tool.httpClient(); + for (int i = 0; i < 2 * cores; i++) { + Tool.send(http, Tool.get(url)); + } + inFlight.reset(); + long startedAt = System.nanoTime(); + List replies = Tool.collect(Tool.fire(http, options.requests(), i -> Tool.get(url), senders)); + millis[run] = (System.nanoTime() - startedAt) / 1_000_000; + peaks[run] = inFlight.peak(); + served[run] = Tool.answers(replies); + } + } + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "", "Platform threads", "Virtual threads"); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "In flight at once (peak)", peaks[0], peaks[1]); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "Answers", served[0], served[1]); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "Time taken", n(millis[0]) + " ms", n(millis[1]) + " ms"); + System.out.println(); + if (millis[1] * 4 >= millis[0] * 3) { + System.out.println("RESULT: NO GAIN. CPU-bound work took " + n(millis[0]) + " ms on platform threads and " + n(millis[1]) + + " ms on virtual threads: both are limited by " + cores + " CPU cores."); + } else { + System.out.println("RESULT: " + n(millis[0]) + " ms on platform threads, " + n(millis[1]) + + " ms on virtual threads. Run it again: with " + cores + " cores the work itself cannot go faster."); + } + System.out.println(); + } + + // ---------------------------------------------------------------- pinning + + private static void pinning() { + int cores = Runtime.getRuntime().availableProcessors(); + int threads = 2 * cores; + long blockMillis = 100; + System.out.println(); + System.out.println("Scenario: pinning | Java " + Runtime.version() + " | " + threads + " virtual threads per case, each blocks for " + + blockMillis + " ms | " + cores + " CPU cores, so " + cores + " carrier threads"); + System.out.println("Pinned: the virtual thread could not unmount while it was blocked, so it held on to its carrier thread."); + System.out.println("Every pinned block is recorded with JFR (event jdk.VirtualThreadPinned), in this JVM."); + System.out.println(); + List results = PinningLab.run(threads, blockMillis); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "Case", "Pinned", "Time", "Why, as JFR reports it"); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "-".repeat(44), "------", "-------", "-".repeat(22)); + boolean synchronizedPins = false; + List stillPins = new ArrayList<>(); + for (PinningLab.Result result : results) { + if (result.unavailable() != null) { + System.out.printf(Locale.ROOT, " %-46s %s%n", result.name(), "skipped: " + result.unavailable()); + continue; + } + List reasons = result.reasons().isEmpty() ? List.of("") : result.reasons(); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", result.name(), result.pinnedEvents(), + n(result.millis()) + " ms", reasons.getFirst()); + for (String reason : reasons.subList(1, reasons.size())) { + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "", "", "", reason); + } + if (result.pinnedEvents() > 0) { + if (result.name().startsWith("synchronized")) { + synchronizedPins = true; + } else { + stillPins.add(result.name().replace("Thread.sleep ", "blocking ")); + } + } + } + System.out.println(); + if (synchronizedPins) { + System.out.println("RESULT: PINNED. On this JVM a virtual thread that blocks inside synchronized is pinned (Java 21 to 23)."); + } else { + System.out.println("RESULT: synchronized does NOT pin on Java " + Runtime.version().feature() + + " (JEP 491). Still pinned: " + String.join("; ", stillPins) + "."); + } + System.out.println(); + } + + // ---------------------------------------------------------------- options + + private static Options parse(String[] args) { + String scenario = "search"; + int requests = 200; + Boolean virtual = null; + long airlineMillis = 500; + Integer poolSize = null; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> scenario = scenario(value(args, ++i, arg)); + case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 2_000); + case "--virtual" -> virtual = onOff(value(args, ++i, arg)); + case "--airline-ms" -> airlineMillis = number(value(args, ++i, arg), arg, 0, 60_000); + case "--pool-size" -> poolSize = number(value(args, ++i, arg), arg, 1, 1_000); + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + return new Options(scenario, requests, virtual, airlineMillis, poolSize); + } + + private static String scenario(String value) { + return switch (value) { + case "search", "cpu", "pooled", "pinning" -> value; + default -> throw new IllegalArgumentException("Unknown scenario: " + value + ". Use search, cpu, pooled or pinning."); + }; + } + + private static Boolean onOff(String value) { + return switch (value) { + case "on", "true" -> true; + case "off", "false" -> false; + default -> throw new IllegalArgumentException("--virtual must be on or off, 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 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 search (default): slow searches that wait for the airline and the database"); + System.out.println(" cpu: CPU-bound requests, on platform threads and then on virtual threads"); + System.out.println(" pooled: the same searches, with every airline call handed to a thread pool (exhibit)"); + System.out.println(" pinning: which kinds of blocking pin a virtual thread on this JVM (no database needed)"); + System.out.println(" --requests how many requests to send at the same moment (default: 200)"); + System.out.println(" --virtual on|off virtual threads for this run only (default: what application.properties says)"); + System.out.println(" --airline-ms how long the airline takes to answer (default: 500)"); + System.out.println(" --pool-size database connections in the pool, for this run only (default: application.properties)"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --virtual on"); + System.out.println(" ./demo --scenario cpu"); + System.out.println(" ./demo --scenario pinning"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java new file mode 100644 index 0000000..5ea4b9d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java @@ -0,0 +1,254 @@ +package com.amigoscode.virtualthreads.demo; + +import static com.amigoscode.virtualthreads.demo.Tool.line; + +import com.amigoscode.virtualthreads.airline.FakeAirline; +import com.amigoscode.virtualthreads.demo.Tool.Reply; +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import java.net.http.HttpClient; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordingStream; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.EnableAsync; + +/** + * Starts the application, sends slow searches at it, and while they are all waiting for the + * airline, looks at the threads: which threads hold the requests, which carrier threads are under + * them, what Tomcat, HikariCP and Postgres see. Then it reports every virtual thread that was + * pinned, from JFR. Run it with ./inspect (or .\inspect on Windows). ./inspect --help lists the flags. + */ +public final class Inspect { + + private static final long AIRLINE_MILLIS = 3_000; + + public static void main(String[] args) throws Exception { + int requests = 50; + Boolean virtual = null; + try { + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--requests" -> requests = Integer.parseInt(args[++i]); + case "--virtual" -> virtual = switch (args[++i]) { + case "on", "true" -> true; + case "off", "false" -> false; + default -> throw new IllegalArgumentException(); + }; + default -> throw new IllegalArgumentException(); + } + } + if (requests < 1 || requests > 1_000) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException e) { + System.out.println("Usage: ./inspect [--requests ] [--virtual on|off] (Windows: .\\inspect ...)"); + System.out.println(); + System.out.println(" --requests how many slow searches to send at the same moment (default: 50)"); + System.out.println(" --virtual on|off virtual threads for this run only (default: what application.properties says)"); + return; + } + if (!Db.isUp()) { + return; + } + List springArgs = new ArrayList<>(List.of("--airline.delay-ms=" + AIRLINE_MILLIS)); + if (virtual != null) { + springArgs.add("--spring.threads.virtual.enabled=" + virtual); + } + try (ConfigurableApplicationContext context = Tool.startApplication(springArgs, AsyncProbe.class); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + inspect(context, requests, senders); + } + } + + /** Only used by inspect: shows which thread runs an @Async method. Not part of the application. */ + @EnableAsync + public static class AsyncProbe { + + @Async + public CompletableFuture whoRunsMe() { + return CompletableFuture.completedFuture(Thread.currentThread().toString()); + } + } + + private static void inspect(ConfigurableApplicationContext context, int requests, ExecutorService senders) throws Exception { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + ServerThreads server = context.getBean(ServerThreads.class); + FakeAirline airline = context.getBean(FakeAirline.class); + HikariDataSource dataSource = Tool.hikari(context); + HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); + TaskExecutor taskExecutor = context.getBean("applicationTaskExecutor", TaskExecutor.class); + boolean virtualOn = context.getEnvironment().getProperty("spring.threads.virtual.enabled", Boolean.class, false); + String baseUrl = Tool.baseUrl(context); + HttpClient http = Tool.httpClient(); + + System.out.println(); + System.out.println("SETTINGS"); + line(" spring.threads.virtual.enabled", virtualOn); + line(" Tomcat runs each request on", server.describe()); + line(" @Async and applicationTaskExecutor", describe(taskExecutor)); + line(" HikariCP pool", "at most " + dataSource.getMaximumPoolSize() + " connections, " + + dataSource.getConnectionTimeout() + " ms connection timeout"); + line(" Postgres max_connections", postgres("show max_connections")); + line(" CPU cores (= carrier threads by default)", Runtime.getRuntime().availableProcessors()); + line(" The airline", "answers in " + airline.delayMillis() + " ms (slowed down for inspect), allows " + + airline.maxConcurrentCalls() + " calls at once"); + + List pinned = new CopyOnWriteArrayList<>(); + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", pinned::add); + jfr.startAsync(); + + // A few searches first, so the snapshot does not show startup work. + for (int i = 0; i < 2; i++) { + Tool.send(http, Tool.get(baseUrl + "/api/fares?route=MAN-BCN")); + } + inFlight.reset(); + int tablesBefore = RateTable.timesBuilt(); + List> futures = Tool.fire(http, requests, i -> Tool.get(baseUrl + "/api/fares?route=LHR-JFK"), senders); + + // Wait until every search is either being served or waiting in Tomcat's queue. + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (inFlight.current() + server.queued() < requests && System.nanoTime() < deadline) { + Thread.sleep(10); + } + Thread.sleep(300); + snapshot(requests, inFlight, server, pool); + + List replies = Tool.collect(futures); + System.out.println(); + System.out.println("AFTER ALL " + requests + " SEARCHES WERE ANSWERED"); + line(" Answers", Tool.answers(replies)); + line(" Rate tables built for them", RateTable.timesBuilt() - tablesBefore); + line(" An @Async method ran on", context.getBean(AsyncProbe.class).whoRunsMe().get()); + jfr.stop(); + } + pinningReport(pinned); + System.out.println(); + } + + private static void snapshot(int requests, InFlightRequests inFlight, ServerThreads server, HikariPoolMXBean pool) throws Exception { + List live = inFlight.liveThreads(); + long virtual = live.stream().filter(Thread::isVirtual).count(); + long mounted = live.stream().filter(thread -> InFlightRequests.carrierOf(thread) != null).count(); + System.out.println(); + System.out.println("WHILE " + requests + " SEARCHES WAIT (a snapshot)"); + line(" Requests in flight", inFlight.current()); + line(" Requests waiting in Tomcat's queue", server.queued()); + line(" Threads holding them", virtual + " virtual, " + (live.size() - virtual) + " platform"); + if (virtual > 0) { + line(" Virtual threads mounted on a carrier now", mounted + " of " + virtual); + line(" Carriers they started on", inFlight.carriers().size() + " (" + Tool.some(new ArrayList<>(inFlight.carriers()), 2) + ")"); + } + line(" Platform threads in the whole JVM", ManagementFactory.getThreadMXBean().getThreadCount()); + line(" HikariCP connections", "active " + pool.getActiveConnections() + ", idle " + pool.getIdleConnections() + + ", requests waiting for one " + pool.getThreadsAwaitingConnection()); + line(" Postgres sessions of this app, by state", postgres(""" + select coalesce(string_agg(state || ': ' || n, ', ' order by state), 'none') + from (select state, count(*) as n + from pg_stat_activity + where datname = current_database() and backend_type = 'client backend' + and application_name = 'PostgreSQL JDBC Driver' and pid <> pg_backend_pid() + group by state) s + """)); + System.out.println(); + System.out.println(" Three of the request threads, as Thread.toString() prints them:"); + live.stream().limit(3).forEach(thread -> System.out.println(" " + thread)); + System.out.println(" Where the first one is waiting (top of its stack):"); + if (!live.isEmpty()) { + StackTraceElement[] stack = live.getFirst().getStackTrace(); + List frames = new ArrayList<>(); + for (StackTraceElement frame : stack) { + String text = frame.getClassName() + "." + frame.getMethodName(); + if (frame.getClassName().startsWith("com.amigoscode") || frames.size() < 4) { + frames.add(text); + } + if (frame.getClassName().startsWith("com.amigoscode.virtualthreads.fares.FareController")) { + break; + } + } + frames.forEach(frame -> System.out.println(" " + frame)); + } + } + + private static void pinningReport(List events) { + System.out.println(); + System.out.println("PINNING (JFR event jdk.VirtualThreadPinned, recorded during this run)"); + if (events.isEmpty()) { + System.out.println(" none. No virtual thread was pinned to its carrier while it blocked."); + return; + } + Map byReason = new LinkedHashMap<>(); + for (RecordedEvent event : events) { + String reason = event.hasField("pinnedReason") ? event.getString("pinnedReason") : "(no reason given)"; + byReason.merge(reason + " | at " + firstApplicationFrame(event), 1, Integer::sum); + } + System.out.println(" " + events.size() + " pinned blocks:"); + byReason.forEach((reason, count) -> System.out.println(" " + count + " x " + reason)); + } + + private static String firstApplicationFrame(RecordedEvent event) { + if (event.getStackTrace() == null) { + return "(no stack trace)"; + } + for (RecordedFrame frame : event.getStackTrace().getFrames()) { + String type = frame.getMethod().getType().getName(); + if (!type.startsWith("java.") && !type.startsWith("jdk.") && !type.startsWith("sun.")) { + return type + "." + frame.getMethod().getName(); + } + } + return "(JDK code only)"; + } + + private static String describe(TaskExecutor executor) { + String type = executor.getClass().getSimpleName(); + if (executor instanceof org.springframework.core.task.SimpleAsyncTaskExecutor simple) { + return type + ": a new " + (isVirtual(simple) ? "virtual" : "platform") + " thread for every task" + + (simple.getConcurrencyLimit() > 0 ? ", at most " + simple.getConcurrencyLimit() + " at once" : ", no limit"); + } + if (executor instanceof org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor pool) { + return type + ": a pool of " + pool.getCorePoolSize() + " platform threads" + + (pool.getQueueCapacity() == Integer.MAX_VALUE ? ", unbounded queue" : ", queue of " + pool.getQueueCapacity()); + } + return type; + } + + private static boolean isVirtual(org.springframework.core.task.SimpleAsyncTaskExecutor executor) { + CompletableFuture virtual = new CompletableFuture<>(); + executor.execute(() -> virtual.complete(Thread.currentThread().isVirtual())); + return virtual.join(); + } + + private static String postgres(String sql) { + try (Connection connection = Db.connect(); Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(sql)) { + return result.next() ? result.getString(1) : ""; + } catch (Exception e) { + return "(could not ask Postgres: " + e.getMessage() + ")"; + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java new file mode 100644 index 0000000..55d7a36 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java @@ -0,0 +1,200 @@ +package com.amigoscode.virtualthreads.demo; + +import com.amigoscode.virtualthreads.VirtualThreadsApplication; +import com.zaxxer.hikari.HikariDataSource; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +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.function.IntSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** What the demo and inspect tools share: starting the application quietly and sending HTTP requests at it. */ +final class Tool { + + /** One answer. Status -1 means the request itself failed (see body). */ + record Reply(int status, String body) { + + String code() { + return status == 200 ? "OK" : json(body, "code"); + } + } + + private Tool() { + } + + /** Starts the real application on a free port, with the logging turned down. */ + static ConfigurableApplicationContext startApplication(List extraArgs, Class... extraSources) { + List> sources = new ArrayList<>(List.of(VirtualThreadsApplication.class)); + sources.addAll(List.of(extraSources)); + SpringApplication app = new SpringApplication(sources.toArray(Class[]::new)); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + List args = new ArrayList<>(List.of( + "--server.port=0", + "--server.shutdown=immediate", + "--logging.level.root=WARN", + // A failed request is counted and shown as one line instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--logging.level.com.zaxxer.hikari=OFF")); + args.addAll(extraArgs); + return app.run(args.toArray(String[]::new)); + } + + static String baseUrl(ConfigurableApplicationContext context) { + return "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + } + + /** The demo's own HTTP client. Its helper tasks run on virtual threads, so it adds no platform threads. */ + static HttpClient httpClient() { + return HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(10)) + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + } + + static HttpRequest get(String url) { + return HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(); + } + + /** Starts {@code requests} requests at the same moment and returns without waiting for them. */ + static List> fire(HttpClient http, int requests, IntFunction request, ExecutorService senders) { + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(requests); + for (int i = 0; i < requests; i++) { + int index = i; + futures.add(senders.submit(() -> { + go.await(); + return send(http, request.apply(index)); + })); + } + go.countDown(); + return futures; + } + + static Reply send(HttpClient http, HttpRequest request) { + try { + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + return new Reply(response.statusCode(), response.body()); + } catch (Exception e) { + return new Reply(-1, e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + static List collect(List> futures) throws Exception { + List replies = new ArrayList<>(futures.size()); + for (Future future : futures) { + replies.add(future.get()); + } + return replies; + } + + /** "200 x 200 OK" or "40 x 200 OK, 160 x 503 DB_POOL_TIMEOUT". */ + static String answers(List replies) { + Map counts = new LinkedHashMap<>(); + replies.stream().sorted((a, b) -> Integer.compare(a.status(), b.status())) + .forEach(reply -> counts.merge(reply.status() + " " + reply.code(), 1, Integer::sum)); + List parts = new ArrayList<>(); + counts.forEach((answer, count) -> parts.add(count + " x " + answer)); + return String.join(", ", parts); + } + + static HikariDataSource hikari(ConfigurableApplicationContext context) { + return context.getBean(HikariDataSource.class); + } + + /** The value of one field in a small JSON answer, or null. Good enough for the flat answers of this app. */ + static String json(String body, String field) { + Matcher matcher = Pattern.compile("\"" + field + "\"\\s*:\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|[-0-9.]+|true|false)") + .matcher(body == null ? "" : body); + if (!matcher.find()) { + return null; + } + return matcher.group(2) != null ? matcher.group(2) : matcher.group(1); + } + + /** 20000 -> "20,000". */ + static String n(long number) { + return String.format(Locale.ROOT, "%,d", number); + } + + static void line(String label, Object value) { + System.out.printf(Locale.ROOT, "%-46s %s%n", label, value); + } + + /** Short list for people: "a, b, c ... (20)". */ + static String some(List values, int max) { + List sorted = values.stream().sorted(Tool::naturalOrder).toList(); + if (sorted.size() <= max) { + return String.join(", ", sorted); + } + return String.join(", ", sorted.subList(0, max)) + " ... " + sorted.getLast(); + } + + /** Sorts "exec-2" before "exec-10". */ + private static int naturalOrder(String a, String b) { + String prefixA = a.replaceAll("\\d+$", ""); + String prefixB = b.replaceAll("\\d+$", ""); + if (!prefixA.equals(prefixB) || prefixA.equals(a) || prefixB.equals(b)) { + return a.compareTo(b); + } + return Long.compare(Long.parseLong(a.substring(prefixA.length())), Long.parseLong(b.substring(prefixB.length()))); + } + + /** Looks at a few numbers every 5 ms while something runs, and remembers the highest value of each. */ + static final class Sampler implements AutoCloseable { + + private final Map gauges; + private final Map highest = new ConcurrentHashMap<>(); + private volatile boolean running = true; + private final CompletableFuture done = new CompletableFuture<>(); + + Sampler(Map gauges) { + this.gauges = gauges; + Thread.ofPlatform().daemon().name("demo-sampler").start(() -> { + while (running) { + sample(); + try { + Thread.sleep(5); + } catch (InterruptedException e) { + break; + } + } + sample(); + done.complete(null); + }); + } + + private void sample() { + gauges.forEach((name, gauge) -> highest.merge(name, gauge.getAsInt(), Math::max)); + } + + int highest(String name) { + return highest.getOrDefault(name, 0); + } + + @Override + public void close() { + running = false; + done.join(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java new file mode 100644 index 0000000..e12ad8b --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java @@ -0,0 +1,70 @@ +package com.amigoscode.virtualthreads.exhibit; + +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * EXHIBIT for Task 6. Do not fix, do not copy. + * + *

The other way people "limit" the calls to the airline: hand every call to a fixed pool of + * fares.max-airline-calls platform threads and wait for the Future. It does cap the airline calls. + * It also brings back everything virtual threads removed: a pool of platform threads sized by + * hand, an unbounded queue in front of it, and a second thread per request (the request thread + * sits parked on Future.get while a pool thread makes the call, so anything the request thread + * carries in a ThreadLocal is not there). Run ./demo --scenario pooled and compare. + */ +@RestController +public class PooledFareController implements DisposableBean { + + private final AirlineClient airline; + private final InFlightRequests inFlight; + private final ExecutorService airlinePool; + + public PooledFareController(AirlineClient airline, InFlightRequests inFlight, + @Value("${fares.max-airline-calls:50}") int poolSize) { + this.airline = airline; + this.inFlight = inFlight; + this.airlinePool = Executors.newFixedThreadPool(poolSize, + Thread.ofPlatform().name("airline-pool-", 1).daemon().factory()); + } + + @GetMapping("/api/fares/pooled") + public Map search(@RequestParam String route) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + Thread requestThread = Thread.currentThread(); + AtomicReference callThread = new AtomicReference<>(); + AirlineQuote quote = airlinePool.submit(() -> { + callThread.set(Thread.currentThread()); + return airline.quote(route); + }).get(); + return Map.of("route", route, "airline", quote.airline(), "priceCents", quote.priceCents(), + "requestThread", requestThread.getName(), "requestThreadVirtual", requestThread.isVirtual(), + "airlineCalledFrom", callThread.get().getName(), "airlineCalledFromVirtual", callThread.get().isVirtual()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted", e); + } catch (ExecutionException e) { + if (e.getCause() instanceof RuntimeException runtime) { + throw runtime; + } + throw new AirlineUnavailableException("The airline call failed", e.getCause()); + } + } + + @Override + public void destroy() { + airlinePool.shutdownNow(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java new file mode 100644 index 0000000..a0140e6 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java @@ -0,0 +1,35 @@ +package com.amigoscode.virtualthreads.fares; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class FareController { + + private final FareService fares; + private final RouteRepository routes; + private final InFlightRequests inFlight; + + public FareController(FareService fares, RouteRepository routes, InFlightRequests inFlight) { + this.fares = fares; + this.routes = routes; + this.inFlight = inFlight; + } + + /** GET /api/fares?route=LHR-JFK¤cy=GBP: slow, it waits for the airline. */ + @GetMapping("/api/fares") + public FareQuote search(@RequestParam String route, @RequestParam(defaultValue = "GBP") String currency) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + return fares.search(route, currency); + } + } + + /** GET /api/routes: fast, one small query. Not counted as in flight. */ + @GetMapping("/api/routes") + public List routes() { + return routes.findAll(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java new file mode 100644 index 0000000..5b76f99 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java @@ -0,0 +1,10 @@ +package com.amigoscode.virtualthreads.fares; + +import java.math.BigDecimal; + +/** + * The answer to a search. {@code servedBy} and {@code virtual} are not something a real API would + * return: they are here so you can see which thread did the work. + */ +public record FareQuote(String route, String airline, BigDecimal price, String currency, String servedBy, boolean virtual) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java new file mode 100644 index 0000000..fe6062f --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java @@ -0,0 +1,70 @@ +package com.amigoscode.virtualthreads.fares; + +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.money.ExchangeRates; +import java.math.BigDecimal; +import java.util.concurrent.Semaphore; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * A fare search: look up the route, ask the airline for a price (slow), convert it into the + * customer's currency, save the search. + */ +@Service +public class FareService { + + private final RouteRepository routes; + private final SearchRepository searches; + private final AirlineClient airline; + private final ExchangeRates rates; + + /** + * At most fares.max-airline-calls calls to the airline at the same time. A request over the + * limit waits here for a permit, on its own virtual thread, instead of being refused by the + * airline with a 429. + */ + private final Semaphore airlineCalls; + + public FareService(RouteRepository routes, SearchRepository searches, AirlineClient airline, ExchangeRates rates, + @Value("${fares.max-airline-calls:50}") int maxAirlineCalls) { + this.routes = routes; + this.searches = searches; + this.airline = airline; + this.rates = rates; + this.airlineCalls = new Semaphore(maxAirlineCalls); + } + + /** + * Not @Transactional: a transaction holds a database connection from its first statement to + * its commit, and this method spends half a second waiting for the airline. Each statement + * below borrows a connection for a few milliseconds and gives it straight back. + */ + public FareQuote search(String routeCode, String currency) { + Route route = routes.find(routeCode).orElseThrow(() -> new UnknownRouteException(routeCode)); + + AirlineQuote quote = askAirline(route.code()); + + BigDecimal price = rates.fromUsd(quote.priceCents(), currency); + Thread thread = Thread.currentThread(); + FareQuote fare = new FareQuote(route.code(), quote.airline(), price, currency, thread.getName(), thread.isVirtual()); + searches.save(fare); + return fare; + } + + private AirlineQuote askAirline(String route) { + try { + airlineCalls.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted while waiting for a free airline call", e); + } + try { + return airline.quote(route); + } finally { + airlineCalls.release(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/Route.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/Route.java new file mode 100644 index 0000000..2b8dbce --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/Route.java @@ -0,0 +1,4 @@ +package com.amigoscode.virtualthreads.fares; + +public record Route(String code, String origin, String destination) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java new file mode 100644 index 0000000..8f1f5cc --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java @@ -0,0 +1,27 @@ +package com.amigoscode.virtualthreads.fares; + +import java.util.List; +import java.util.Optional; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +@Repository +public class RouteRepository { + + private final JdbcTemplate jdbc; + + public RouteRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public Optional find(String code) { + return jdbc.query("select code, origin, destination from route where code = ?", + (rs, row) -> new Route(rs.getString("code"), rs.getString("origin"), rs.getString("destination")), code) + .stream().findFirst(); + } + + public List findAll() { + return jdbc.query("select code, origin, destination from route order by code", + (rs, row) -> new Route(rs.getString("code"), rs.getString("origin"), rs.getString("destination"))); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java new file mode 100644 index 0000000..d32958a --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java @@ -0,0 +1,22 @@ +package com.amigoscode.virtualthreads.fares; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +/** Saves every search, with the thread that served it. */ +@Repository +public class SearchRepository { + + private final JdbcTemplate jdbc; + + public SearchRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public void save(FareQuote quote) { + jdbc.update(""" + insert into fare_search (route, airline, price, currency, served_by, virtual) + values (?, ?, ?, ?, ?, ?) + """, quote.route(), quote.airline(), quote.price(), quote.currency(), quote.servedBy(), quote.virtual()); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java new file mode 100644 index 0000000..b955b03 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java @@ -0,0 +1,8 @@ +package com.amigoscode.virtualthreads.fares; + +public class UnknownRouteException extends RuntimeException { + + public UnknownRouteException(String route) { + super("Unknown route: " + route); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java new file mode 100644 index 0000000..ae48ac5 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java @@ -0,0 +1,21 @@ +package com.amigoscode.virtualthreads.money; + +import java.math.BigDecimal; +import org.springframework.stereotype.Component; + +/** + * Converts the airline's price in US dollars into the customer's currency. + * + *

The rate table is read-only once it is built, so one table is shared by every thread. A + * ThreadLocal copy only paid off while threads were pooled and reused: a virtual thread serves one + * request and is gone, so a ThreadLocal would build a new table for every request. + */ +@Component +public class ExchangeRates { + + private final RateTable table = RateTable.build(); + + public BigDecimal fromUsd(long usdCents, String currency) { + return table.fromUsd(usdCents, currency); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java new file mode 100644 index 0000000..c76ed74 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java @@ -0,0 +1,73 @@ +package com.amigoscode.virtualthreads.money; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Currency; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Exchange rates, precomputed so that a conversion is one array lookup: the rate between every pair + * of 30 currencies for each of the last 90 days. 81,000 numbers, about 650 KB. Building it takes a + * few milliseconds, so it is meant to be built once and reused. + * + *

Read-only once built: every field is final and nothing writes to the array after the + * constructor, so one table can safely be shared by any number of threads. Nothing to change here. + */ +public final class RateTable { + + /** Units of each currency for one US dollar, today. */ + static final List CODES = List.of( + "USD", "GBP", "EUR", "JPY", "CHF", "CAD", "AUD", "NZD", "SEK", "NOK", + "DKK", "PLN", "CZK", "HUF", "RON", "TRY", "ZAR", "INR", "SGD", "HKD", + "CNY", "KRW", "MXN", "BRL", "AED", "SAR", "ILS", "THB", "MYR", "PHP"); + private static final double[] PER_USD = { + 1.00, 0.79, 0.92, 151.00, 0.88, 1.37, 1.52, 1.66, 10.50, 10.70, + 6.87, 3.98, 23.10, 362.00, 4.58, 32.20, 18.40, 83.30, 1.35, 7.82, + 7.24, 1350.00, 17.10, 5.05, 3.67, 3.75, 3.70, 36.40, 4.72, 56.10}; + static final int DAYS = 90; + public static final long BYTES = (long) CODES.size() * CODES.size() * DAYS * Double.BYTES; + + private static final AtomicInteger BUILT = new AtomicInteger(); + + /** [day][from][to], flattened. Day 0 is today. */ + private final double[] rates; + + private RateTable() { + int n = CODES.size(); + double[] table = new double[n * n * DAYS]; + for (int day = 0; day < DAYS; day++) { + // Older days drift a little, so the history is not just 90 copies of today. + double drift = 1.0 + day * 0.0005; + for (int from = 0; from < n; from++) { + for (int to = 0; to < n; to++) { + double rate = PER_USD[to] / PER_USD[from]; + table[(day * n + from) * n + to] = day == 0 ? rate : rate * drift; + } + } + } + this.rates = table; + BUILT.incrementAndGet(); + } + + public static RateTable build() { + return new RateTable(); + } + + /** How many tables have been built since the JVM started. */ + public static int timesBuilt() { + return BUILT.get(); + } + + /** Today's price, in {@code currency}, of {@code usdCents} US cents, rounded to the currency's decimals. */ + public BigDecimal fromUsd(long usdCents, String currency) { + int to = CODES.indexOf(currency); + if (to < 0) { + throw new UnknownCurrencyException(currency); + } + double rate = rates[to]; // day 0, from USD (index 0) + return BigDecimal.valueOf(usdCents, 2) + .multiply(BigDecimal.valueOf(rate)) + .setScale(Currency.getInstance(currency).getDefaultFractionDigits(), RoundingMode.HALF_EVEN); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java new file mode 100644 index 0000000..dc50ef1 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java @@ -0,0 +1,8 @@ +package com.amigoscode.virtualthreads.money; + +public class UnknownCurrencyException extends RuntimeException { + + public UnknownCurrencyException(String currency) { + super("Unknown currency: " + currency); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java new file mode 100644 index 0000000..ad62b7c --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java @@ -0,0 +1,194 @@ +package com.amigoscode.virtualthreads.pinning; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.ReentrantLock; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingStream; + +/** + * Which kinds of blocking pin a virtual thread to its carrier, on the JVM you are running. Each + * case starts some virtual threads that all block for the same time, and JFR records every + * jdk.VirtualThreadPinned event while they run. Used by ./demo --scenario pinning. Nothing to + * change here. + */ +public final class PinningLab { + + /** One case: how many pinned events JFR saw, the reasons it gave, and how long the case took. */ + public record Result(String name, int threads, int pinnedEvents, List reasons, long millis, String unavailable) { + } + + private static volatile long callbackSleepMillis; + private static volatile long staticInitSleepMillis; + + private PinningLab() { + } + + public static List run(int threads, long blockMillis) { + warmUp(); + List results = new ArrayList<>(); + results.add(measure("synchronized, Thread.sleep inside", threads, () -> { + Object lock = new Object(); + synchronized (lock) { + sleep(blockMillis); + } + })); + results.add(measure("synchronized, Object.wait inside", threads, () -> { + Object lock = new Object(); + synchronized (lock) { + try { + lock.wait(blockMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + })); + results.add(measure("ReentrantLock, Thread.sleep inside", threads, () -> { + ReentrantLock lock = new ReentrantLock(); + lock.lock(); + try { + sleep(blockMillis); + } finally { + lock.unlock(); + } + })); + staticInitSleepMillis = blockMillis; // not a field of SlowStaticInit: writing one would initialize the class + results.add(measure("Thread.sleep inside a static initializer", threads, SlowStaticInit::touch)); + Optional qsort = qsort(); + if (qsort.isPresent()) { + callbackSleepMillis = blockMillis; + results.add(measure("Thread.sleep in a callback from native code", threads, () -> sortTwoInts(qsort.get()))); + } else { + results.add(new Result("Thread.sleep in a callback from native code", threads, 0, List.of(), 0, + "qsort from the C library is not available on this platform")); + } + return results; + } + + /** The class initializer runs once, on the first thread that touches the class. It blocks. */ + static final class SlowStaticInit { + + static { + sleep(staticInitSleepMillis); + } + + static void touch() { + } + } + + /** Runs {@code task} once on each of {@code threads} virtual threads, all at the same moment, and records pinning. */ + private static Result measure(String name, int threads, Runnable task) { + List events = new CopyOnWriteArrayList<>(); + long millis; + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", events::add); + jfr.startAsync(); + millis = runOnVirtualThreads(threads, task); + jfr.stop(); + } + List reasons = events.stream() + .map(event -> event.hasField("pinnedReason") ? event.getString("pinnedReason") : "(no reason given by this JVM)") + .map(reason -> reason.replace(PinningLab.class.getName() + "$", "")) + .distinct() + .toList(); + return new Result(name, threads, events.size(), reasons, millis, null); + } + + private static long runOnVirtualThreads(int threads, Runnable task) { + CountDownLatch go = new CountDownLatch(1); + long startedAt; + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + for (int i = 0; i < threads; i++) { + executor.submit(() -> { + go.await(); + task.run(); + return null; + }); + } + startedAt = System.nanoTime(); + go.countDown(); + } + return (System.nanoTime() - startedAt) / 1_000_000; + } + + /** + * The first time the JDK runs this code it loads and initializes some of its own classes, and + * that can pin for a moment. Run everything once, unrecorded, so the cases only show themselves. + */ + private static void warmUp() { + Object lock = new Object(); + ReentrantLock reentrantLock = new ReentrantLock(); + runOnVirtualThreads(4, () -> { + synchronized (lock) { + sleep(1); + } + reentrantLock.lock(); + try { + sleep(1); + } finally { + reentrantLock.unlock(); + } + }); + qsort().ifPresent(handle -> { + callbackSleepMillis = 0; + runOnVirtualThreads(2, () -> sortTwoInts(handle)); + }); + } + + private static Optional qsort() { + try { + Linker linker = Linker.nativeLinker(); + return linker.defaultLookup().find("qsort").map(address -> linker.downcallHandle(address, + FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.ADDRESS))); + } catch (RuntimeException e) { + return Optional.empty(); + } + } + + /** Calls C's qsort on two ints. qsort calls back into {@link #compare}, which sleeps. */ + private static void sortTwoInts(MethodHandle qsort) { + try (Arena arena = Arena.ofConfined()) { + Linker linker = Linker.nativeLinker(); + MethodHandle compare = MethodHandles.lookup().findStatic(PinningLab.class, "compare", + MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class)); + MemorySegment callback = linker.upcallStub(compare, FunctionDescriptor.of(ValueLayout.JAVA_INT, + ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT), + ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT)), arena); + MemorySegment numbers = arena.allocateFrom(ValueLayout.JAVA_INT, 2, 1); + qsort.invokeExact(numbers, 2L, ValueLayout.JAVA_INT.byteSize(), callback); + } catch (Throwable e) { + throw new IllegalStateException("Calling qsort failed", e); + } + } + + private static int compare(MemorySegment a, MemorySegment b) { + sleep(callbackSleepMillis); + return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0)); + } + + private static void sleep(long millis) { + if (millis <= 0) { + return; + } + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java new file mode 100644 index 0000000..b1167f4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java @@ -0,0 +1,107 @@ +package com.amigoscode.virtualthreads.threads; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.stereotype.Component; + +/** + * Counts the requests that are being served right now, and remembers which threads served them. + * The controllers call {@link #enter()} first thing and close the ticket last thing, so "in flight" + * means: a thread has picked the request up and is working on it, or waiting inside it. Used by + * the demo, inspect and the tests. Nothing to change here. + */ +@Component +public class InFlightRequests { + + private final AtomicInteger current = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger served = new AtomicInteger(); + private final AtomicInteger virtual = new AtomicInteger(); + private final AtomicInteger platform = new AtomicInteger(); + private final Set threadNames = ConcurrentHashMap.newKeySet(); + private final Set carriers = ConcurrentHashMap.newKeySet(); + private final Set live = ConcurrentHashMap.newKeySet(); + + /** One request. Close it when the request is finished (try-with-resources). */ + public interface Ticket extends AutoCloseable { + @Override + void close(); + } + + public Ticket enter() { + Thread thread = Thread.currentThread(); + int now = current.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + served.incrementAndGet(); + (thread.isVirtual() ? virtual : platform).incrementAndGet(); + threadNames.add(thread.getName()); + String carrier = carrierOf(thread); + if (carrier != null) { + carriers.add(carrier); + } + live.add(thread); + return () -> { + live.remove(thread); + current.decrementAndGet(); + }; + } + + /** + * The carrier a virtual thread is mounted on right now, read from its toString(): + * {@code VirtualThread[#52,tomcat-handler-0]/runnable@ForkJoinPool-1-worker-3}. Null for a + * platform thread, and for a virtual thread that is unmounted (parked) at this moment. + */ + public static String carrierOf(Thread thread) { + String text = thread.toString(); + int at = text.lastIndexOf('@'); + return thread.isVirtual() && at > 0 ? text.substring(at + 1) : null; + } + + /** Requests being served right now. */ + public int current() { + return current.get(); + } + + /** The most requests that were in flight at the same moment since the last reset. */ + public int peak() { + return peak.get(); + } + + public int served() { + return served.get(); + } + + public int servedByVirtualThreads() { + return virtual.get(); + } + + public int servedByPlatformThreads() { + return platform.get(); + } + + /** The names of the threads that served requests since the last reset. */ + public Set threadNames() { + return Set.copyOf(threadNames); + } + + /** The carrier threads the virtual request threads were mounted on when they started. */ + public Set carriers() { + return Set.copyOf(carriers); + } + + /** The threads serving a request right now. */ + public List liveThreads() { + return List.copyOf(live); + } + + public void reset() { + peak.set(current.get()); + served.set(0); + virtual.set(0); + platform.set(0); + threadNames.clear(); + carriers.clear(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java new file mode 100644 index 0000000..d66360f --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java @@ -0,0 +1,55 @@ +package com.amigoscode.virtualthreads.threads; + +import java.util.concurrent.Executor; +import org.apache.tomcat.util.threads.ThreadPoolExecutor; +import org.springframework.boot.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; +import org.springframework.boot.web.server.context.WebServerApplicationContext; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +/** + * Looks inside Tomcat: which executor runs the requests, and, for a pool of platform threads, how + * many threads it has and how many requests are waiting in its queue. Used by the demo, inspect + * and the tests. Nothing to change here. + */ +@Component +public class ServerThreads { + + private final ApplicationContext context; + + public ServerThreads(ApplicationContext context) { + this.context = context; + } + + /** The executor Tomcat hands every request to. */ + public Executor executor() { + WebServer server = ((WebServerApplicationContext) context).getWebServer(); + return ((TomcatWebServer) server).getTomcat().getConnector().getProtocolHandler().getExecutor(); + } + + /** True when Tomcat starts a new virtual thread for every request. */ + public boolean virtual() { + return !(executor() instanceof ThreadPoolExecutor); + } + + /** Requests Tomcat has read and could not hand to a thread yet: every pooled thread is busy. */ + public int queued() { + return executor() instanceof ThreadPoolExecutor pool ? pool.getQueue().size() : 0; + } + + /** Pooled platform threads that are serving a request right now. 0 for virtual threads. */ + public int busyThreads() { + return executor() instanceof ThreadPoolExecutor pool ? pool.getActiveCount() : 0; + } + + /** One line for people: what kind of executor this is. */ + public String describe() { + Executor executor = executor(); + if (executor instanceof ThreadPoolExecutor pool) { + return "ThreadPoolExecutor: a pool of at most " + pool.getMaximumPoolSize() + + " platform threads, then a queue"; + } + return executor.getClass().getSimpleName() + ": a new virtual thread for every request, no limit"; + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/application.properties b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/application.properties new file mode 100644 index 0000000..8d0e3a3 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/application.properties @@ -0,0 +1,29 @@ +spring.application.name=virtual-threads + +# Postgres from compose.yaml. Port 5457 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5457/fares} +spring.datasource.username=${DB_USER:fares} +spring.datasource.password=${DB_PASSWORD:fares} +spring.sql.init.mode=always + +# Tomcat serves each request on one thread. 20 instead of the default 200, so the limit is easy to +# see with a few hundred requests. Do not change it: the tests count on it. +server.tomcat.threads.max=20 + +# Virtual threads: one new virtual thread per request instead of a pooled platform thread. +spring.threads.virtual.enabled=true + +# The connection pool: one connection for each of Tomcat's 20 threads (the HikariCP default is 10). +# A request that cannot get a connection within 2 seconds fails. The default is 30 seconds; most +# teams set a few seconds, so that a request fails fast instead of hanging. +spring.datasource.hikari.maximum-pool-size=20 +spring.datasource.hikari.connection-timeout=2000 + +# How many airline calls this application makes at the same time, at most (Task 5). +fares.max-airline-calls=50 + +# The airline. In this project it is a small fake HTTP server inside the application (see +# FakeAirline): it answers after airline.delay-ms, and refuses with 429 Too Many Requests when more +# than airline.max-concurrent-calls calls are in progress at once. +airline.delay-ms=500 +airline.max-concurrent-calls=50 diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/schema.sql new file mode 100644 index 0000000..9f773cd --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/main/resources/schema.sql @@ -0,0 +1,27 @@ +-- Runs on every start (spring.sql.init.mode=always). + +create table if not exists route ( + code varchar(7) primary key, + origin varchar(60) not null, + destination varchar(60) not null +); + +insert into route (code, origin, destination) values + ('LHR-JFK', 'London Heathrow', 'New York JFK'), + ('LHR-CDG', 'London Heathrow', 'Paris Charles de Gaulle'), + ('MAN-BCN', 'Manchester', 'Barcelona'), + ('LGW-LIS', 'London Gatwick', 'Lisbon'), + ('EDI-AMS', 'Edinburgh', 'Amsterdam') +on conflict (code) do nothing; + +-- One row per search: what was found, and which thread served the request. +create table if not exists fare_search ( + id bigserial primary key, + route varchar(7) not null references route (code), + airline varchar(60) not null, + price numeric(12, 2) not null, + currency char(3) not null, + served_by varchar(200) not null, + virtual boolean not null, + searched_at timestamptz not null default now() +); diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java new file mode 100644 index 0000000..1b8fec9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java @@ -0,0 +1,85 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.IntegrationTest; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.TestPropertySource; + +/** + * Task 5. Virtual threads on. The airline allows 5 calls at once (the stub refuses the 6th, like the + * real one answers 429), and the application is configured with fares.max-airline-calls=5. + */ +@Tag("task5") +@TestPropertySource(properties = {"spring.threads.virtual.enabled=true", "fares.max-airline-calls=5"}) +class AirlineLimitIT extends IntegrationTest { + + private static final int LIMIT = 5; + private static final int SEARCHES = 15; + + @BeforeEach + void theAirlineAllowsFive() { + airline.refuseAbove(LIMIT); + } + + @Test + @DisplayName("Airline limit: 15 searches at once, the airline allows 5: it never has more than 5 calls in progress") + void neverMoreThanFiveAtTheAirline() { + sendFifteenAndRelease(); + + assertThat(airline.peak()) + .withFailMessage("The airline had %d calls in progress at the same moment. It allows %d.", airline.peak(), LIMIT) + .isLessThanOrEqualTo(LIMIT); + } + + @Test + @DisplayName("Airline limit: all 15 get a fare. A search over the limit waits for a free slot instead of failing") + void everySearchGetsAFare() { + List replies = sendFifteenAndRelease(); + + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + } + + @Test + @DisplayName("Airline limit: the airline is called on the request's own virtual thread, not handed to a thread pool") + void calledOnTheRequestThread() { + for (int i = 0; i < 3; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + assertThat(airline.fromOtherThreads()).as("airline calls made by a thread that is not the request's thread").isZero(); + assertThat(airline.fromVirtualThreads()).as("airline calls made from a virtual thread").isEqualTo(3); + } + + @Test + @DisplayName("Airline limit: a failed airline call gives its slot back. After 5 failures in a row, the next 5 searches still get a fare") + void aFailedCallGivesItsSlotBack() { + airline.failNext(LIMIT); + for (int i = 0; i < LIMIT; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(10)).status()).as("a search while the airline is down").isEqualTo(502); + } + + List replies = Searches.start(port, LIMIT, Searches.SEARCH, Duration.ofSeconds(10)).finish(); + + assertThat(Searches.failures(replies)).as("searches after the airline came back").isEmpty(); + } + + /** + * Sends 15 searches and holds the airline until either all 15 got there (nothing limits them), or + * exactly 5 got there and the other 10 are in flight and stay where they are: waiting for a slot. + */ + private List sendFifteenAndRelease() { + airline.holdEveryCall(); + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(300), () -> airline.arrivals() == SEARCHES + || (airline.arrivals() == LIMIT && inFlight.current() == SEARCHES)); + airline.release(); + return searches.finish(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java new file mode 100644 index 0000000..f1da300 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java @@ -0,0 +1,74 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 3. Plain Java, no Spring: what the JVM does with a virtual thread that blocks. These tests + * pass from the start. They document what ./inspect shows you. + */ +@Tag("task3") +class CarrierThreadsTest { + + private static final int THREADS = 1_000; + + private final CountDownLatch gate = new CountDownLatch(1); + private final Set carriers = ConcurrentHashMap.newKeySet(); + private final List threads = new ArrayList<>(); + + @BeforeEach + void startThousandBlockedVirtualThreads() { + // Once unrecorded, so the JDK has loaded the classes it needs before we look. + Thread.ofVirtual().start(() -> InFlightRequests.carrierOf(Thread.currentThread())); + for (int i = 0; i < THREADS; i++) { + threads.add(Thread.ofVirtual().name("blocked-", i).start(() -> { + carriers.add(InFlightRequests.carrierOf(Thread.currentThread())); + try { + gate.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + })); + } + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)) + .until(() -> threads.stream().allMatch(thread -> thread.getState() == Thread.State.WAITING)); + } + + @AfterEach + void releaseThem() throws InterruptedException { + gate.countDown(); + for (Thread thread : threads) { + thread.join(); + } + } + + @Test + @DisplayName("Unmount: 1,000 virtual threads are blocked at the same moment, and not one of them is holding a carrier thread") + void blockedVirtualThreadsAreUnmounted() { + List mounted = threads.stream().filter(thread -> InFlightRequests.carrierOf(thread) != null) + .map(Thread::toString).toList(); + + assertThat(mounted).as("blocked virtual threads that are still mounted on a carrier").isEmpty(); + assertThat(threads.getFirst().toString()).as("a blocked virtual thread, as toString() prints it").endsWith("/waiting"); + } + + @Test + @DisplayName("Carriers: those 1,000 virtual threads ran on a handful of carrier threads (about one per CPU core), not on 1,000 OS threads") + void aHandfulOfCarriers() { + assertThat(carriers).as("carrier threads").allSatisfy(carrier -> assertThat(carrier).startsWith("ForkJoinPool")); + assertThat(carriers.size()).as("carrier threads used by %d virtual threads", THREADS).isLessThan(THREADS / 10); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/Check.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/Check.java new file mode 100644 index 0000000..e1c05de --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/Check.java @@ -0,0 +1,119 @@ +package com.amigoscode.virtualthreads; + +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. Task 6 is an inspection task: you answer questions, no code. Tasks 1, 3 + * and 8 are inspection tasks too, and their tests pass from the start: they document what you see. + */ + 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 thread-per-request ceiling"); + TASKS.put("2", "Task 2: Turn on virtual threads"); + TASKS.put("3", "Task 3: Inspect virtual threads: carriers, mount and unmount"); + TASKS.put("4", "Task 4: Fix the new bottleneck: the connection pool"); + TASKS.put("5", "Task 5: Limit the airline calls with a Semaphore, not a thread pool"); + TASKS.put("7", "Task 7: Fix the ThreadLocal cache"); + TASKS.put("8", "Task 8: Inspect pinning on Java 25"); + } + + 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/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java new file mode 100644 index 0000000..4f66b61 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java @@ -0,0 +1,69 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.OnVirtualThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 4. Virtual threads on, a pool of 10 connections that gives up after 500 ms. The airline stub + * holds every call at a gate. The test waits until every search has either reached the airline or + * already failed, then looks. + */ +@Tag("task4") +class ConnectionPoolIT extends OnVirtualThreads { + + private static final int SEARCHES = 30; + + @Test + @DisplayName("Pool: while 30 searches wait for the airline, none of them is holding a database connection") + void noConnectionHeldWhileWaitingForTheAirline() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntil(() -> airline.arrivals() + searches.failed() == SEARCHES); + int held = pool().getActiveConnections(); + int atTheAirline = airline.arrivals(); + + airline.release(); + searches.finish(); + assertThat(held) + .withFailMessage("%d of the pool's 10 connections were held by the %d searches that were waiting for the airline.", + held, atTheAirline) + .isZero(); + } + + @Test + @DisplayName("Pool: 30 searches at the same moment, a pool of 10 connections: every search gets a fare, none times out waiting for a connection") + void nobodyTimesOutWaitingForAConnection() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntil(() -> airline.arrivals() + searches.failed() == SEARCHES); + + airline.release(); + List replies = searches.finish(); + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + } + + @Test + @DisplayName("Pool: every search is still saved, with its price and the thread that served it") + void everySearchIsSaved() { + Searches.Reply reply = Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)); + + assertThat(reply.status()).as("answer to the search: " + reply.body()).isEqualTo(200); + List> rows = jdbc.queryForList("select route, airline, price, currency, served_by, virtual from fare_search"); + assertThat(rows).as("rows in fare_search").hasSize(1); + assertThat(rows.getFirst().get("route")).isEqualTo("LHR-JFK"); + assertThat(rows.getFirst().get("price").toString()).as("price of 412.50 US dollars in pounds").isEqualTo("325.88"); + assertThat(rows.getFirst().get("currency")).isEqualTo("GBP"); + assertThat(reply.body()).contains("\"servedBy\":\"" + rows.getFirst().get("served_by") + "\""); + assertThat(rows.getFirst().get("virtual")).isEqualTo(true); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java new file mode 100644 index 0000000..5130c6a --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java @@ -0,0 +1,35 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.virtualthreads.money.ExchangeRates; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import java.math.BigDecimal; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Unit tests: whatever you change about how the table is kept, the conversions stay right. */ +@Tag("task7") +class ExchangeRatesTest { + + @Test + @DisplayName("Rates: 100.00 US dollars is 79.00 pounds, 92.00 euros and 15100 yen, also from 100 virtual threads at once") + void convertsFromAnyThread() throws Exception { + ExchangeRates rates = new ExchangeRates(); + List>> results; + try (ExecutorService threads = Executors.newVirtualThreadPerTaskExecutor()) { + results = threads.invokeAll(java.util.Collections.nCopies(100, () -> List.of( + rates.fromUsd(10_000, "GBP"), rates.fromUsd(10_000, "EUR"), rates.fromUsd(10_000, "JPY")))); + } + for (Future> result : results) { + assertThat(result.get()).containsExactly(new BigDecimal("79.00"), new BigDecimal("92.00"), new BigDecimal("15100")); + } + assertThatThrownBy(() -> rates.fromUsd(10_000, "XYZ")).isInstanceOf(UnknownCurrencyException.class); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java new file mode 100644 index 0000000..07769b4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java @@ -0,0 +1,98 @@ +package com.amigoscode.virtualthreads; + +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.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.fares.FareController; +import com.amigoscode.virtualthreads.fares.FareQuote; +import com.amigoscode.virtualthreads.fares.FareService; +import com.amigoscode.virtualthreads.fares.UnknownRouteException; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.math.BigDecimal; +import java.sql.SQLTransientConnectionException; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.CannotCreateTransactionException; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, FareService is a stub. They pass + * from the start and must keep passing: whatever you change, a search that cannot be served gets a + * clear error, never a 500. + */ +@Tag("baseline") +class FareControllerTest { + + @Test + @DisplayName("HTTP: a search returns 200 with the route, the airline, the price and the thread that served it") + void searchReturnsTheFare() throws Exception { + api(() -> new FareQuote("LHR-JFK", "Skyway", new BigDecimal("325.88"), "GBP", "tomcat-handler-7", true)) + .perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.route").value("LHR-JFK")) + .andExpect(jsonPath("$.price").value(325.88)) + .andExpect(jsonPath("$.currency").value("GBP")) + .andExpect(jsonPath("$.servedBy").value("tomcat-handler-7")) + .andExpect(jsonPath("$.virtual").value(true)); + } + + @Test + @DisplayName("HTTP: an unknown route returns 404 UNKNOWN_ROUTE") + void unknownRouteReturnsNotFound() throws Exception { + api(() -> { + throw new UnknownRouteException("XXX-YYY"); + }).perform(get("/api/fares?route=XXX-YYY")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.code").value("UNKNOWN_ROUTE")); + } + + @Test + @DisplayName("HTTP: an unknown currency returns 400 UNKNOWN_CURRENCY") + void unknownCurrencyReturnsBadRequest() throws Exception { + api(() -> { + throw new UnknownCurrencyException("XYZ"); + }).perform(get("/api/fares?route=LHR-JFK¤cy=XYZ")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("UNKNOWN_CURRENCY")); + } + + @Test + @DisplayName("HTTP: the airline refusing the call (429 Too Many Requests) returns 503 AIRLINE_BUSY") + void airlineBusyReturnsServiceUnavailable() throws Exception { + api(() -> { + throw new AirlineBusyException("The airline answered 429 Too Many Requests for LHR-JFK"); + }).perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.code").value("AIRLINE_BUSY")); + } + + @Test + @DisplayName("HTTP: no database connection within the timeout returns 503 DB_POOL_TIMEOUT, not a 500") + void poolTimeoutReturnsServiceUnavailable() throws Exception { + api(() -> { + throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", + new SQLTransientConnectionException("HikariPool-1 - Connection is not available, request timed out after 2000ms")); + }).perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.code").value("DB_POOL_TIMEOUT")); + } + + /** The controller wired to a FareService whose search does whatever the test says. */ + private static MockMvc api(Supplier search) { + FareService stub = new FareService(null, null, null, null, 50) { + @Override + public FareQuote search(String route, String currency) { + return search.get(); + } + }; + return MockMvcBuilders.standaloneSetup(new FareController(stub, null, new InFlightRequests())) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PinningTest.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PinningTest.java new file mode 100644 index 0000000..c3590ba --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PinningTest.java @@ -0,0 +1,182 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordingStream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 8. Plain Java, no Spring. JFR records a jdk.VirtualThreadPinned event every time a virtual + * thread blocks while it cannot unmount. These tests record those events in this JVM while a virtual + * thread blocks in different ways. They pass from the start: they document Java 25. + */ +@Tag("task8") +class PinningTest { + + private static final Object LOCK = new Object(); + + /** Not a field of SlowToInitialize: reading one from the test thread would wait for its initializer. */ + private static final CountDownLatch STATIC_INIT_GATE = new CountDownLatch(1); + + @Test + @DisplayName("Java 25: a virtual thread that blocks inside synchronized is not pinned (JEP 491, since Java 24)") + void synchronizedDoesNotPin() throws Exception { + CountDownLatch gate = new CountDownLatch(1); + Runnable blockInsideSynchronized = () -> { + synchronized (LOCK) { + block(gate); + } + }; + warmUp(); + + List pinned = record(() -> { + Thread holder = Thread.ofVirtual().start(blockInsideSynchronized); + Thread waiter = Thread.ofVirtual().start(blockInsideSynchronized); // has to wait for the monitor + waitUntilBlocked(holder, waiter); + gate.countDown(); + join(holder, waiter); + }); + + assertThat(pinned).as("pinned events while two virtual threads block inside and in front of synchronized").isEmpty(); + } + + @Test + @DisplayName("Java 25: Object.wait() inside synchronized does not pin either") + void objectWaitDoesNotPin() throws Exception { + Object monitor = new Object(); + boolean[] ready = {false}; + Runnable waitForReady = () -> { + synchronized (monitor) { + while (!ready[0]) { + try { + monitor.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + }; + + List pinned = record(() -> { + Thread waiter = Thread.ofVirtual().start(waitForReady); + waitUntilBlocked(waiter); + synchronized (monitor) { + ready[0] = true; + monitor.notifyAll(); + } + join(waiter); + }); + + assertThat(pinned).as("pinned events while a virtual thread waits in Object.wait()").isEmpty(); + } + + @Test + @DisplayName("Java 25: a virtual thread that blocks inside a static initializer is still pinned") + void blockingInAStaticInitializerPins() throws Exception { + List pinned = record(() -> { + Thread first = Thread.ofVirtual().start(SlowToInitialize::touch); + waitUntilBlocked(first); + STATIC_INIT_GATE.countDown(); + join(first); + }); + + assertThat(pinned).as("pinned events while a virtual thread blocks in a static initializer").isNotEmpty(); + assertThat(pinned.getFirst().getString("pinnedReason")).as("the reason JFR gives").contains(""); + } + + /** Its static initializer blocks until the test opens the gate. Used by one test only: a class is initialized once. */ + static final class SlowToInitialize { + + static { + PinningTest.block(STATIC_INIT_GATE); + } + + static void touch() { + } + } + + /** Records the jdk.VirtualThreadPinned events of this test class's threads while {@code work} runs. */ + private static List record(ThrowingRunnable work) throws Exception { + List events = new CopyOnWriteArrayList<>(); + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", events::add); + jfr.startAsync(); + work.run(); + jfr.stop(); + } + return events.stream().filter(PinningTest::fromThisTest).toList(); + } + + private static boolean fromThisTest(RecordedEvent event) { + if (event.getStackTrace() == null) { + return false; + } + for (RecordedFrame frame : event.getStackTrace().getFrames()) { + if (frame.getMethod().getType().getName().startsWith(PinningTest.class.getName())) { + return true; + } + } + return false; + } + + /** + * The same thing once, unrecorded, on another lock. The first time, the JDK loads and initializes + * classes it needs for this (and that can pin for a moment), so we only look at the second time. + */ + private static void warmUp() throws InterruptedException { + Object lock = new Object(); + CountDownLatch gate = new CountDownLatch(1); + Runnable blockInsideSynchronized = () -> { + synchronized (lock) { + block(gate); + } + }; + Thread holder = Thread.ofVirtual().start(blockInsideSynchronized); + Thread waiter = Thread.ofVirtual().start(blockInsideSynchronized); + waitUntilBlocked(holder, waiter); + gate.countDown(); + join(holder, waiter); + } + + private static void waitUntilBlocked(Thread... threads) { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(5)).until(() -> { + for (Thread thread : threads) { + Thread.State state = thread.getState(); + if (state != Thread.State.WAITING && state != Thread.State.BLOCKED && state != Thread.State.TIMED_WAITING) { + return false; + } + } + return true; + }); + } + + private static void join(Thread... threads) throws InterruptedException { + for (Thread thread : threads) { + thread.join(Duration.ofSeconds(10)); + } + } + + static void block(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run() throws Exception; + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java new file mode 100644 index 0000000..db9c214 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.OnPlatformThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. These tests pass on purpose: they pin down the thread-per-request ceiling. The airline + * stub holds every call at a gate, so the test decides when the slow call ends. Nothing is left to + * timing: the test waits until every request is either being served or queued, then counts. + */ +@Tag("task1") +class PlatformThreadsIT extends OnPlatformThreads { + + @Test + @DisplayName("Platform threads: 30 slow searches, Tomcat has 20 threads: 20 are in flight, the other 10 wait in Tomcat's queue") + void twentyInFlightTenQueued() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, 30); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == 30); + + assertThat(inFlight.current()).as("searches in flight").isEqualTo(20); + assertThat(server.queued()).as("searches waiting in Tomcat's queue").isEqualTo(10); + + airline.release(); + List replies = searches.finish(); + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + assertThat(inFlight.peak()).as("most searches in flight at the same moment").isEqualTo(20); + } + + @Test + @DisplayName("Platform threads: while all 20 threads wait for the airline, even a fast GET /api/routes waits in the same queue") + void aFastRequestWaitsBehindTheSlowOnes() { + airline.holdEveryCall(); + Searches searches = Searches.start(port, 30); + waitUntil(() -> inFlight.current() == 20 && server.queued() == 10); + + CompletableFuture routes = CompletableFuture.supplyAsync( + () -> Searches.send(port, "/api/routes", Duration.ofSeconds(30))); + waitUntil(() -> server.queued() == 11); + + assertThat(routes).as("GET /api/routes, while every Tomcat thread is waiting for the airline").isNotDone(); + + airline.release(); + assertThat(routes.join().status()).as("GET /api/routes once the threads are free").isEqualTo(200); + searches.finish(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java new file mode 100644 index 0000000..f9eb9db --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java @@ -0,0 +1,27 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.support.OnPlatformThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Why the ThreadLocal looked fine for years: pooled threads are reused. Passes from the start. */ +@Tag("task7") +class RateTableOnPlatformThreadsIT extends OnPlatformThreads { + + @Test + @DisplayName("ThreadLocal: on a pool of 20 platform threads, 50 searches build the rate table at most 20 times (why it looked fine)") + void builtAtMostOncePerPooledThread() { + int before = RateTable.timesBuilt(); + + List replies = Searches.start(port, 50).finish(); + + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + assertThat(RateTable.timesBuilt() - before).as("rate tables built by 50 searches on 20 pooled threads").isLessThanOrEqualTo(20); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java new file mode 100644 index 0000000..3a53b84 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java @@ -0,0 +1,32 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.support.OnVirtualThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Every search converts the airline's price with the rate table. How often is it built? */ +@Tag("task7") +class RateTableOnVirtualThreadsIT extends OnVirtualThreads { + + @Test + @DisplayName("ThreadLocal: 20 searches on virtual threads build the rate table at most once, not once per request") + void builtAtMostOnce() { + int before = RateTable.timesBuilt(); + + for (int i = 0; i < 20; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + int built = RateTable.timesBuilt() - before; + assertThat(built) + .withFailMessage("20 searches built the rate table %d times (%,d KB). Each virtual thread serves one request," + + " so a ThreadLocal is never reused.", built, built * RateTable.BYTES / 1024) + .isLessThanOrEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java new file mode 100644 index 0000000..ef71663 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.IntegrationTest; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 2. The application exactly as application.properties configures it. The airline stub holds + * every call at a gate; the test waits until every request is either being served or queued in + * Tomcat, then counts. + */ +@Tag("task2") +class VirtualThreadsIT extends IntegrationTest { + + private static final int SEARCHES = 50; + + @Test + @DisplayName("Virtual threads: 50 slow searches are all in flight at the same moment. Tomcat's limit of 20 threads no longer applies") + void allFiftyInFlight() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == SEARCHES); + int inFlightNow = inFlight.current(); + int queuedNow = server.queued(); + + airline.release(); + searches.finish(); + assertThat(inFlightNow) + .withFailMessage("Only %d of %d searches were in flight; %d waited in Tomcat's queue for a free thread.", + inFlightNow, SEARCHES, queuedNow) + .isEqualTo(SEARCHES); + } + + @Test + @DisplayName("Virtual threads: every request is served by a virtual thread") + void servedByVirtualThreads() { + for (int i = 0; i < 5; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + assertThat(inFlight.servedByPlatformThreads()) + .withFailMessage("%d of 5 requests were served by platform threads: %s", + inFlight.servedByPlatformThreads(), inFlight.threadNames()) + .isZero(); + assertThat(inFlight.servedByVirtualThreads()).as("requests served by virtual threads").isEqualTo(5); + } + + @Test + @DisplayName("Virtual threads: the 50 request threads run on a few carrier threads, platform threads of a ForkJoinPool, fewer than 50") + void aFewCarrierThreads() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == SEARCHES); + airline.release(); + searches.finish(); + + Set carriers = inFlight.carriers(); + assertThat(carriers) + .withFailMessage("No carrier threads: the requests were served by platform threads, which run on their own OS thread.") + .isNotEmpty(); + assertThat(carriers).as("carrier threads").allSatisfy(carrier -> assertThat(carrier).startsWith("ForkJoinPool")); + assertThat(carriers.size()).as("carrier threads under %d virtual threads", SEARCHES).isLessThan(SEARCHES); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java new file mode 100644 index 0000000..9d1dd1d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java @@ -0,0 +1,122 @@ +package com.amigoscode.virtualthreads.support; + +import com.amigoscode.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Replaces the airline in the integration tests. Instead of sleeping, every call can be held at a + * gate until the test releases it, so a test decides exactly when the "slow" call ends, and can + * count how many callers are inside at the same moment. It can also behave like the real airline's + * rate limit, and fail on purpose. + */ +public class ControllableAirline implements AirlineClient { + + public static final long PRICE_CENTS = 41_250; + + private final InFlightRequests inFlight; + + private final AtomicInteger arrivals = new AtomicInteger(); + private final AtomicInteger inProgress = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger fromVirtualThreads = new AtomicInteger(); + private final AtomicInteger fromOtherThreads = new AtomicInteger(); + private final AtomicInteger failuresLeft = new AtomicInteger(); + private volatile int refuseAbove; + private volatile CountDownLatch gate; + + public ControllableAirline(InFlightRequests inFlight) { + this.inFlight = inFlight; + } + + public void reset() { + release(); + arrivals.set(0); + peak.set(0); + fromVirtualThreads.set(0); + fromOtherThreads.set(0); + failuresLeft.set(0); + refuseAbove = 0; + gate = null; + } + + /** Every call waits at the gate until {@link #release()}. */ + public void holdEveryCall() { + gate = new CountDownLatch(1); + } + + public void release() { + CountDownLatch current = gate; + if (current != null) { + current.countDown(); + } + } + + /** Like the real airline: a call that finds more than {@code limit} calls in progress is refused (429). */ + public void refuseAbove(int limit) { + refuseAbove = limit; + } + + /** The next {@code calls} calls fail straight away, as if the airline were down. */ + public void failNext(int calls) { + failuresLeft.set(calls); + } + + /** Calls that reached the airline since the last reset. */ + public int arrivals() { + return arrivals.get(); + } + + /** The most calls that were in progress at the same moment. */ + public int peak() { + return peak.get(); + } + + public int fromVirtualThreads() { + return fromVirtualThreads.get(); + } + + /** Calls made by a thread that is not the thread serving the request. */ + public int fromOtherThreads() { + return fromOtherThreads.get(); + } + + @Override + public AirlineQuote quote(String route) { + if (failuresLeft.getAndDecrement() > 0) { + throw new AirlineUnavailableException("The airline is down (a failure the test asked for)"); + } + Thread caller = Thread.currentThread(); + if (caller.isVirtual()) { + fromVirtualThreads.incrementAndGet(); + } + if (!inFlight.liveThreads().contains(caller)) { + fromOtherThreads.incrementAndGet(); + } + arrivals.incrementAndGet(); + int now = inProgress.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + try { + boolean tooMany = refuseAbove > 0 && now > refuseAbove; + CountDownLatch current = gate; + if (current != null && !current.await(30, TimeUnit.SECONDS)) { + throw new AirlineUnavailableException("The test never released the airline gate"); + } + if (tooMany) { + throw new AirlineBusyException("The airline answered 429 Too Many Requests: " + now + + " calls were in progress, it allows " + refuseAbove); + } + return new AirlineQuote("Skyway", PRICE_CENTS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted", e); + } finally { + inProgress.decrementAndGet(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java new file mode 100644 index 0000000..a9453e8 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java @@ -0,0 +1,103 @@ +package com.amigoscode.virtualthreads.support; + +import static org.awaitility.Awaitility.await; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.time.Duration; +import java.util.concurrent.Callable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +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 start the real application, with Tomcat on a free port, against + * a real Postgres started by Testcontainers (Docker must be running). Only the airline is replaced, + * by a stub the tests control. The threads, Tomcat's executor and the connection pool are the real + * ones: that is what these tests are about. One Postgres container is shared by every test class. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + // Several test classes run with different settings, so several applications (and pools) are open at once. + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine") + .withCommand("postgres", "-c", "max_connections=200"); + + 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 + ControllableAirline controllableAirline(InFlightRequests inFlight) { + return new ControllableAirline(inFlight); + } + } + + @Value("${local.server.port}") + protected int port; + + @Autowired + protected ControllableAirline airline; + + @Autowired + protected InFlightRequests inFlight; + + @Autowired + protected ServerThreads server; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private HikariDataSource dataSource; + + @BeforeEach + void cleanState() { + airline.reset(); + inFlight.reset(); + jdbc.execute("truncate table fare_search restart identity"); + } + + @AfterEach + void letEveryoneGo() { + airline.release(); + } + + protected HikariPoolMXBean pool() { + return dataSource.getHikariPoolMXBean(); + } + + /** Waits until {@code condition} is true. Not a timing assertion: it only decides when to look. */ + protected static void waitUntil(Callable condition) { + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)).until(condition); + } + + /** Waits until {@code condition} has been true, without a break, for {@code steady}. */ + protected static void waitUntilSteady(Duration steady, Callable condition) { + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)).during(steady).until(condition); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java new file mode 100644 index 0000000..98a99d9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java @@ -0,0 +1,14 @@ +package com.amigoscode.virtualthreads.support; + +import org.springframework.test.context.TestPropertySource; + +/** + * The application as it was before virtual threads, whatever application.properties says: Tomcat's + * pool of 20 platform threads. The connection timeout is long, so nothing times out while a test + * holds every thread on purpose. + */ +@TestPropertySource(properties = { + "spring.threads.virtual.enabled=false", + "spring.datasource.hikari.connection-timeout=30000"}) +public abstract class OnPlatformThreads extends IntegrationTest { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java new file mode 100644 index 0000000..0b810de --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java @@ -0,0 +1,15 @@ +package com.amigoscode.virtualthreads.support; + +import org.springframework.test.context.TestPropertySource; + +/** + * Virtual threads on, whatever application.properties says, with a small connection pool (10) that + * gives up quickly (500 ms), and no limit on airline calls that a test could run into. + */ +@TestPropertySource(properties = { + "spring.threads.virtual.enabled=true", + "spring.datasource.hikari.maximum-pool-size=10", + "spring.datasource.hikari.connection-timeout=500", + "fares.max-airline-calls=100"}) +public abstract class OnVirtualThreads extends IntegrationTest { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/Searches.java b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/Searches.java new file mode 100644 index 0000000..522be63 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/java/com/amigoscode/virtualthreads/support/Searches.java @@ -0,0 +1,101 @@ +package com.amigoscode.virtualthreads.support; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +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.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** Sends HTTP requests at the running application, all at the same moment, like many customers would. */ +public final class Searches { + + public static final String SEARCH = "/api/fares?route=LHR-JFK"; + + /** One answer. Status -1 means the request itself failed (see body). */ + public record Reply(int status, String body) { + } + + private static final HttpClient HTTP = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(10)) + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + + private final ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor(); + private final List> futures = new ArrayList<>(); + private final AtomicInteger failed = new AtomicInteger(); + + private Searches() { + } + + /** Starts {@code count} requests for {@code path} at the same moment and returns straight away. */ + public static Searches start(int port, int count, String path, Duration timeout) { + Searches searches = new Searches(); + CountDownLatch go = new CountDownLatch(1); + for (int i = 0; i < count; i++) { + searches.futures.add(searches.senders.submit(() -> { + go.await(); + Reply reply = send(port, path, timeout); + if (reply.status() != 200) { + searches.failed.incrementAndGet(); + } + return reply; + })); + } + go.countDown(); + return searches; + } + + public static Searches start(int port, int count) { + return start(port, count, SEARCH, Duration.ofSeconds(30)); + } + + /** Requests that have already come back with something other than 200. */ + public int failed() { + return failed.get(); + } + + /** Waits for every answer. */ + public List finish() { + List replies = new ArrayList<>(); + try { + for (Future future : futures) { + replies.add(future.get(60, TimeUnit.SECONDS)); + } + return replies; + } catch (Exception e) { + throw new IllegalStateException("A request did not come back: " + e, e); + } finally { + senders.shutdownNow(); + } + } + + public static Reply send(int port, String path, Duration timeout) { + try { + HttpResponse response = HTTP.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) + .timeout(timeout).GET().build(), HttpResponse.BodyHandlers.ofString()); + return new Reply(response.statusCode(), response.body()); + } catch (Exception e) { + return new Reply(-1, e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + /** "20 of 30 searches failed, for example: 503 {...}", or "" when all 200. */ + public static String failures(List replies) { + List failed = replies.stream().filter(reply -> reply.status() != 200).toList(); + if (failed.isEmpty()) { + return ""; + } + String body = failed.getFirst().body(); + return failed.size() + " of " + replies.size() + " searches failed, for example: " + failed.getFirst().status() + " " + + (body.length() > 220 ? body.substring(0, 220) + "..." : body); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/solution/src/test/resources/logback-test.xml b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/resources/logback-test.xml new file mode 100644 index 0000000..1296fbb --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/solution/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + diff --git a/java/concepts/junior-mid/18-virtual-threads/start/.mvn/jvm.config b/java/concepts/junior-mid/18-virtual-threads/start/.mvn/jvm.config new file mode 100644 index 0000000..07a2d88 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/start/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/18-virtual-threads/start/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/start/check b/java/concepts/junior-mid/18-virtual-threads/start/check new file mode 100755 index 0000000..be8b918 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.Check -Dexec.classpathScope=test -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/check.cmd b/java/concepts/junior-mid/18-virtual-threads/start/check.cmd new file mode 100644 index 0000000..169aada --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/compose.yaml b/java/concepts/junior-mid/18-virtual-threads/start/compose.yaml new file mode 100644 index 0000000..6ee7af3 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/compose.yaml @@ -0,0 +1,16 @@ +name: virtual-threads +services: + postgres: + image: postgres:17-alpine + container_name: virtual-threads-postgres + environment: + POSTGRES_DB: fares + POSTGRES_USER: fares + POSTGRES_PASSWORD: fares + ports: + - "5457:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U fares -d fares"] + interval: 2s + timeout: 2s + retries: 20 diff --git a/java/concepts/junior-mid/18-virtual-threads/start/demo b/java/concepts/junior-mid/18-virtual-threads/start/demo new file mode 100755 index 0000000..ed936b4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Demo -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/demo.cmd b/java/concepts/junior-mid/18-virtual-threads/start/demo.cmd new file mode 100644 index 0000000..5441daf --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Demo" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/inspect b/java/concepts/junior-mid/18-virtual-threads/start/inspect new file mode 100755 index 0000000..2ca5934 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Inspect -Dexec.args="$*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/inspect.cmd b/java/concepts/junior-mid/18-virtual-threads/start/inspect.cmd new file mode 100644 index 0000000..cf8de79 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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.virtualthreads.demo.Inspect" "-Dexec.args=%*" diff --git a/java/concepts/junior-mid/18-virtual-threads/start/mvnw b/java/concepts/junior-mid/18-virtual-threads/start/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/start/mvnw.cmd b/java/concepts/junior-mid/18-virtual-threads/start/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/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/18-virtual-threads/start/pom.xml b/java/concepts/junior-mid/18-virtual-threads/start/pom.xml new file mode 100644 index 0000000..171571d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.2 + + + + com.amigoscode + virtual-threads + 0.0.1-SNAPSHOT + virtual-threads + Virtual threads: watch the thread-per-request ceiling, lift it, then find the limits that are left + + + 25 + 3.5.0 + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-jdbc + + + 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.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/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java new file mode 100644 index 0000000..63133bc --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/ApiExceptionHandler.java @@ -0,0 +1,68 @@ +package com.amigoscode.virtualthreads; + +import com.amigoscode.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.fares.UnknownRouteException; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import java.sql.SQLTransientConnectionException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** Turns the failures a fare search can run into into clear JSON errors. Nothing to change here. */ +@RestControllerAdvice +public class ApiExceptionHandler { + + public record ApiError(String code, String message) { + } + + @ExceptionHandler(UnknownRouteException.class) + public ResponseEntity unknownRoute(UnknownRouteException e) { + return error(HttpStatus.NOT_FOUND, "UNKNOWN_ROUTE", e.getMessage()); + } + + @ExceptionHandler(UnknownCurrencyException.class) + public ResponseEntity unknownCurrency(UnknownCurrencyException e) { + return error(HttpStatus.BAD_REQUEST, "UNKNOWN_CURRENCY", e.getMessage()); + } + + /** The airline refused the call: too many calls were in progress at once. */ + @ExceptionHandler(AirlineBusyException.class) + public ResponseEntity airlineBusy(AirlineBusyException e) { + return error(HttpStatus.SERVICE_UNAVAILABLE, "AIRLINE_BUSY", e.getMessage()); + } + + @ExceptionHandler(AirlineUnavailableException.class) + public ResponseEntity airlineUnavailable(AirlineUnavailableException e) { + return error(HttpStatus.BAD_GATEWAY, "AIRLINE_ERROR", e.getMessage()); + } + + /** + * No database connection became free within spring.datasource.hikari.connection-timeout. + * Spring wraps HikariCP's SQLTransientConnectionException: in CannotCreateTransactionException + * when a @Transactional method starts, in CannotGetJdbcConnectionException for a plain query. + */ + @ExceptionHandler({CannotCreateTransactionException.class, DataAccessResourceFailureException.class}) + public ResponseEntity noConnection(RuntimeException e) { + Throwable cause = e; + while (cause != null && !(cause instanceof SQLTransientConnectionException)) { + cause = cause.getCause(); + } + if (cause == null) { + return error(HttpStatus.SERVICE_UNAVAILABLE, "DATABASE_ERROR", e.getMessage()); + } + String message = cause.getMessage(); + if (cause.getCause() != null && cause.getCause().getMessage() != null) { + // For example Postgres refusing a new connection: "FATAL: sorry, too many clients already". + message += " Caused by: " + cause.getCause().getMessage().lines().findFirst().orElse(""); + } + return error(HttpStatus.SERVICE_UNAVAILABLE, "DB_POOL_TIMEOUT", message); + } + + private static ResponseEntity error(HttpStatus status, String code, String message) { + return ResponseEntity.status(status).body(new ApiError(code, message)); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java new file mode 100644 index 0000000..cc3fb04 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/VirtualThreadsApplication.java @@ -0,0 +1,12 @@ +package com.amigoscode.virtualthreads; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VirtualThreadsApplication { + + public static void main(String[] args) { + SpringApplication.run(VirtualThreadsApplication.class, args); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java new file mode 100644 index 0000000..83735f6 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineBusyException.java @@ -0,0 +1,9 @@ +package com.amigoscode.virtualthreads.airline; + +/** The airline answered 429 Too Many Requests: too many calls were in progress at once. */ +public class AirlineBusyException extends RuntimeException { + + public AirlineBusyException(String message) { + super(message); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java new file mode 100644 index 0000000..9f33998 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineClient.java @@ -0,0 +1,10 @@ +package com.amigoscode.virtualthreads.airline; + +/** + * Asks an airline for the price of a route. A blocking call: the calling thread waits until the + * airline answers, which takes about half a second. + */ +public interface AirlineClient { + + AirlineQuote quote(String route); +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java new file mode 100644 index 0000000..eb77c24 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineQuote.java @@ -0,0 +1,5 @@ +package com.amigoscode.virtualthreads.airline; + +/** What the airline answers: its name and the price in US cents. */ +public record AirlineQuote(String airline, long priceCents) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java new file mode 100644 index 0000000..2aaa2c2 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/AirlineUnavailableException.java @@ -0,0 +1,13 @@ +package com.amigoscode.virtualthreads.airline; + +/** The airline could not be reached, or answered with an error. */ +public class AirlineUnavailableException extends RuntimeException { + + public AirlineUnavailableException(String message) { + super(message); + } + + public AirlineUnavailableException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java new file mode 100644 index 0000000..960918e --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/FakeAirline.java @@ -0,0 +1,129 @@ +package com.amigoscode.virtualthreads.airline; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Stands in for the airline's API: a small HTTP server on its own port, started with the + * application. It answers GET /quote?route=LHR-JFK after airline.delay-ms, and, like a real partner + * API, it has a rate limit: when more than airline.max-concurrent-calls calls are in progress at + * once, it answers 429 Too Many Requests straight away. Nothing to change here. + */ +@Component +public class FakeAirline implements DisposableBean { + + private final long delayMillis; + private final int maxConcurrentCalls; + private final HttpServer server; + private final ExecutorService handlers = Executors.newVirtualThreadPerTaskExecutor(); + + private final AtomicInteger inProgress = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger answered = new AtomicInteger(); + private final AtomicInteger refused = new AtomicInteger(); + + public FakeAirline(@Value("${airline.delay-ms:500}") long delayMillis, + @Value("${airline.max-concurrent-calls:50}") int maxConcurrentCalls) throws IOException { + this.delayMillis = delayMillis; + this.maxConcurrentCalls = maxConcurrentCalls; + this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 1000); + server.createContext("/quote", this::quote); + server.setExecutor(handlers); + server.start(); + } + + public URI baseUri() { + return URI.create("http://127.0.0.1:" + server.getAddress().getPort()); + } + + public long delayMillis() { + return delayMillis; + } + + public int maxConcurrentCalls() { + return maxConcurrentCalls; + } + + /** Calls the airline is working on right now. */ + public int inProgress() { + return inProgress.get(); + } + + /** The most calls that were in progress at the same moment since the last reset. */ + public int peak() { + return peak.get(); + } + + public int answered() { + return answered.get(); + } + + /** Calls refused with 429 because too many were in progress. */ + public int refused() { + return refused.get(); + } + + public void resetCounters() { + peak.set(inProgress.get()); + answered.set(0); + refused.set(0); + } + + private void quote(HttpExchange exchange) throws IOException { + int now = inProgress.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + try { + if (now > maxConcurrentCalls) { + refused.incrementAndGet(); + send(exchange, 429, "{\"error\":\"too many calls in progress, the limit is " + maxConcurrentCalls + "\"}"); + return; + } + sleep(delayMillis); + String route = exchange.getRequestURI().getQuery() == null ? "" : exchange.getRequestURI().getQuery().replace("route=", ""); + answered.incrementAndGet(); + send(exchange, 200, "{\"airline\":\"Skyway\",\"priceCents\":" + priceCents(route) + "}"); + } finally { + inProgress.decrementAndGet(); + } + } + + /** A fixed price per route, between 99.00 and 698.99 dollars. */ + static long priceCents(String route) { + return 9_900 + Math.floorMod(route.hashCode(), 60_000); + } + + private static void send(HttpExchange exchange, int status, String json) throws IOException { + byte[] body = json.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public void destroy() { + server.stop(0); + handlers.shutdownNow(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java new file mode 100644 index 0000000..370f472 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/airline/HttpAirlineClient.java @@ -0,0 +1,65 @@ +package com.amigoscode.virtualthreads.airline; + +import java.net.http.HttpClient; +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientException; + +/** + * Calls the airline over HTTP. {@code quote} blocks: the calling thread waits for the answer. On a + * platform thread that is an OS thread doing nothing for half a second. On a virtual thread the JVM + * unmounts it while it waits, and the carrier thread serves someone else. Nothing to change here. + */ +@Component +public class HttpAirlineClient implements AirlineClient { + + private final RestClient http; + private final Set callerThreads = ConcurrentHashMap.newKeySet(); + + public HttpAirlineClient(FakeAirline airline) { + HttpClient client = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)) + // The JDK client's own helper tasks run on virtual threads, so they do not add + // platform threads to what the demo counts. + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + JdkClientHttpRequestFactory requests = new JdkClientHttpRequestFactory(client); + requests.setReadTimeout(Duration.ofSeconds(30)); + this.http = RestClient.builder().baseUrl(airline.baseUri().toString()).requestFactory(requests).build(); + } + + @Override + public AirlineQuote quote(String route) { + Thread caller = Thread.currentThread(); + callerThreads.add((caller.isVirtual() ? "virtual " : "platform ") + caller.getName()); + try { + return http.get() + .uri("/quote?route={route}", route) + .retrieve() + .onStatus(status -> status.value() == HttpStatus.TOO_MANY_REQUESTS.value(), (request, response) -> { + throw new AirlineBusyException("The airline answered 429 Too Many Requests for " + route); + }) + .body(AirlineQuote.class); + } catch (AirlineBusyException e) { + throw e; + } catch (RestClientException e) { + throw new AirlineUnavailableException("The airline did not answer for " + route + ": " + e.getMessage(), e); + } + } + + /** "virtual tomcat-handler-12" or "platform airline-pool-3": one entry per thread that called the airline. */ + public Set callerThreads() { + return Set.copyOf(callerThreads); + } + + public void resetCallerThreads() { + callerThreads.clear(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java new file mode 100644 index 0000000..0b9e761 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/cpu/CpuController.java @@ -0,0 +1,48 @@ +package com.amigoscode.virtualthreads.cpu; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * CPU-bound work: hash a value over and over. No waiting at all, the thread computes the whole + * time. Used by ./demo --scenario cpu to show what virtual threads do NOT speed up. Nothing to + * change here. + */ +@RestController +public class CpuController { + + private final InFlightRequests inFlight; + + public CpuController(InFlightRequests inFlight) { + this.inFlight = inFlight; + } + + @GetMapping("/api/cpu") + public Map hash(@RequestParam(defaultValue = "100000") int rounds) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + byte[] value = "fare".getBytes(StandardCharsets.UTF_8); + MessageDigest sha256 = sha256(); + for (int i = 0; i < rounds; i++) { + value = sha256.digest(value); + } + Thread thread = Thread.currentThread(); + return Map.of("rounds", rounds, "hash", HexFormat.of().formatHex(value), + "servedBy", thread.getName(), "virtual", thread.isVirtual()); + } + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Db.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Db.java new file mode 100644 index 0000000..1897ef4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Db.java @@ -0,0 +1,41 @@ +package com.amigoscode.virtualthreads.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:5457/fares"); + static final String USER = env("DB_USER", "fares"); + static final String PASSWORD = env("DB_PASSWORD", "fares"); + + 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/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java new file mode 100644 index 0000000..ef48c8d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Demo.java @@ -0,0 +1,415 @@ +package com.amigoscode.virtualthreads.demo; + +import static com.amigoscode.virtualthreads.demo.Tool.line; +import static com.amigoscode.virtualthreads.demo.Tool.n; + +import com.amigoscode.virtualthreads.airline.FakeAirline; +import com.amigoscode.virtualthreads.airline.HttpAirlineClient; +import com.amigoscode.virtualthreads.demo.Tool.Reply; +import com.amigoscode.virtualthreads.demo.Tool.Sampler; +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.pinning.PinningLab; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.net.http.HttpClient; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.IntSupplier; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Starts the real application, sends many requests at it at the same moment, and prints how many + * were in flight at once, which threads served them, and what ran out. Run it with ./demo (or + * .\demo on Windows). ./demo --help lists the flags. + */ +public final class Demo { + + private static final String ROUTE = "LHR-JFK"; + private static final ThreadMXBean THREADS = ManagementFactory.getThreadMXBean(); + + private record Options(String scenario, int requests, Boolean virtual, long airlineMillis, Integer poolSize) { + } + + 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; + } + switch (options.scenario()) { + case "pinning" -> pinning(); + case "cpu" -> { + if (Db.isUp()) { + cpu(options); + } + } + default -> { + if (Db.isUp()) { + searches(options); + } + } + } + } + + // ---------------------------------------------------------------- search and pooled + + private static void searches(Options options) throws Exception { + boolean pooled = options.scenario().equals("pooled"); + List springArgs = new ArrayList<>(List.of("--airline.delay-ms=" + options.airlineMillis())); + if (options.virtual() != null) { + springArgs.add("--spring.threads.virtual.enabled=" + options.virtual()); + } + if (options.poolSize() != null) { + springArgs.add("--spring.datasource.hikari.maximum-pool-size=" + options.poolSize()); + } + try (ConfigurableApplicationContext context = Tool.startApplication(springArgs); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + ServerThreads server = context.getBean(ServerThreads.class); + FakeAirline airline = context.getBean(FakeAirline.class); + HttpAirlineClient airlineClient = context.getBean(HttpAirlineClient.class); + HikariDataSource dataSource = Tool.hikari(context); + HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); + JdbcTemplate jdbc = context.getBean(JdbcTemplate.class); + String baseUrl = Tool.baseUrl(context); + HttpClient http = Tool.httpClient(); + String path = pooled ? "/api/fares/pooled?route=" + ROUTE : "/api/fares?route=" + ROUTE; + + // Fresh state for every run, and a few throwaway requests so startup work is not measured. + jdbc.execute("truncate table fare_search restart identity"); + for (int i = 0; i < 3; i++) { + Tool.send(http, Tool.get(baseUrl + path)); + } + inFlight.reset(); + airline.resetCounters(); + airlineClient.resetCallerThreads(); + int tablesBefore = RateTable.timesBuilt(); + int platformBefore = THREADS.getThreadCount(); + THREADS.resetPeakThreadCount(); + + System.out.println(); + System.out.println("Scenario: " + options.scenario() + " | " + n(options.requests()) + " searches at GET " + path + + ", all at the same moment"); + System.out.println("Virtual threads: " + (server.virtual() ? "ON" : "OFF") + " | Tomcat: " + server.describe()); + System.out.println("The airline answers in " + airline.delayMillis() + " ms and allows " + airline.maxConcurrentCalls() + + " calls at once | DB pool: " + dataSource.getMaximumPoolSize() + " connections, " + + dataSource.getConnectionTimeout() + " ms timeout"); + System.out.println(); + + Map gauges = new LinkedHashMap<>(); + gauges.put("queued", server::queued); + gauges.put("dbActive", pool::getActiveConnections); + gauges.put("dbWaiting", pool::getThreadsAwaitingConnection); + long startedAt = System.nanoTime(); + List replies; + long fastMillis; + try (Sampler sampler = new Sampler(gauges)) { + List> futures = Tool.fire(http, options.requests(), i -> Tool.get(baseUrl + path), senders); + Future fast = senders.submit(() -> { + Thread.sleep(100); + long sentAt = System.nanoTime(); + Tool.send(http, Tool.get(baseUrl + "/api/routes")); + return (System.nanoTime() - sentAt) / 1_000_000; + }); + replies = Tool.collect(futures); + fastMillis = fast.get(); + long millis = (System.nanoTime() - startedAt) / 1_000_000; + sampler.close(); + + List threadNames = new ArrayList<>(inFlight.threadNames()); + List carriers = new ArrayList<>(inFlight.carriers()); + int virtualServed = inFlight.servedByVirtualThreads(); + int platformServed = inFlight.servedByPlatformThreads(); + + line("Requests in flight at once (peak):", inFlight.peak()); + line("Requests waiting in Tomcat's queue (peak):", sampler.highest("queued")); + line("Airline calls at once (peak):", airline.peak()); + line("Served by:", servedBy(virtualServed, platformServed, threadNames)); + line("Carrier threads under them:", carriers.isEmpty() + ? "none: a platform thread is an OS thread, it is not mounted on anything" + : carriers.size() + " (" + Tool.some(carriers, 3) + ")"); + line("Airline called from:", calledFrom(airlineClient.callerThreads())); + line("Platform threads in the JVM (peak):", THREADS.getPeakThreadCount() + " (" + platformBefore + " before the requests)"); + line("DB connections in use (peak):", sampler.highest("dbActive") + " of " + dataSource.getMaximumPoolSize()); + line("Requests waiting for a DB connection (peak):", sampler.highest("dbWaiting")); + line("Rate tables built during the run:", (RateTable.timesBuilt() - tablesBefore) + + " (" + n((RateTable.timesBuilt() - tablesBefore) * RateTable.BYTES / 1024) + " KB)"); + line("Answers:", Tool.answers(replies)); + replies.stream().filter(reply -> reply.status() != 200).findFirst().ifPresent(reply -> + line(" for example:", reply.status() + " " + shorten(Tool.json(reply.body(), "message") == null + ? reply.body() : Tool.json(reply.body(), "message"), 110))); + line("A fast GET /api/routes sent during the load:", "answered after " + n(fastMillis) + " ms"); + line("Time taken:", n(millis) + " ms"); + System.out.println(); + printResult(options, pooled, replies, inFlight.peak(), carriers.size(), airline, airlineClient, dataSource); + } + } + System.out.println(); + } + + private static void printResult(Options options, boolean pooled, List replies, int peak, int carriers, + FakeAirline airline, HttpAirlineClient airlineClient, HikariDataSource dataSource) { + int total = replies.size(); + long poolTimeouts = replies.stream().filter(reply -> "DB_POOL_TIMEOUT".equals(reply.code())).count(); + long airlineBusy = replies.stream().filter(reply -> "AIRLINE_BUSY".equals(reply.code())).count(); + long otherErrors = replies.stream().filter(reply -> reply.status() != 200).count() - poolTimeouts - airlineBusy; + boolean failed = false; + if (poolTimeouts > 0) { + failed = true; + System.out.println("RESULT: POOL EXHAUSTED. " + poolTimeouts + " of " + total + + " searches failed: no database connection within " + dataSource.getConnectionTimeout() + + " ms (pool of " + dataSource.getMaximumPoolSize() + ")."); + } + if (airlineBusy > 0) { + failed = true; + System.out.println("RESULT: AIRLINE OVERLOADED. " + airlineBusy + " of " + total + + " searches were refused by the airline with 429: it allows " + airline.maxConcurrentCalls() + + " calls at once, it got " + airline.peak() + "."); + } + if (otherErrors > 0) { + failed = true; + System.out.println("RESULT: ERRORS. " + otherErrors + " of " + total + " searches failed."); + } + if (failed) { + return; + } + if (peak < total) { + System.out.println("RESULT: QUEUED. " + total + " requests, at most " + peak + " in flight."); + } else if (pooled) { + long platformCallers = airlineClient.callerThreads().stream().filter(name -> name.startsWith("platform ")).count(); + System.out.println("RESULT: POOLED. " + total + " requests in flight at once, but every airline call was handed to one of " + + platformCallers + " pooled platform threads."); + } else if (carriers == 0) { + System.out.println("RESULT: OK. " + total + " requests in flight at once, on " + total + + " platform threads, at most " + airline.peak() + " at the airline."); + } else { + System.out.println("RESULT: OK. " + total + " requests in flight at once on " + carriers + + " carrier threads, at most " + airline.peak() + " at the airline."); + } + } + + private static String servedBy(int virtual, int platform, List names) { + List parts = new ArrayList<>(); + if (platform > 0) { + List platformNames = names.stream().filter(name -> !name.startsWith("tomcat-handler")).toList(); + parts.add(platformNames.size() + " platform threads (" + Tool.some(platformNames, 2) + ")"); + } + if (virtual > 0) { + List virtualNames = names.stream().filter(name -> name.startsWith("tomcat-handler")).toList(); + parts.add(virtual + " virtual threads (" + Tool.some(virtualNames, 2) + ")"); + } + return String.join(" and ", parts); + } + + private static String calledFrom(java.util.Set callers) { + List virtual = callers.stream().filter(name -> name.startsWith("virtual ")).map(name -> name.substring(8)).toList(); + List platform = callers.stream().filter(name -> name.startsWith("platform ")).map(name -> name.substring(9)).toList(); + List parts = new ArrayList<>(); + if (!virtual.isEmpty()) { + parts.add(virtual.size() + " virtual threads, the request's own thread"); + } + if (!platform.isEmpty()) { + parts.add(platform.size() + " platform threads (" + Tool.some(platform, 2) + ")"); + } + return parts.isEmpty() ? "nobody" : String.join(" and ", parts); + } + + private static String shorten(String text, int max) { + String oneLine = text == null ? "" : text.replaceAll("\\s+", " "); + return oneLine.length() <= max ? oneLine : oneLine.substring(0, max) + "..."; + } + + // ---------------------------------------------------------------- cpu + + private static final int CPU_ROUNDS = 500_000; + + private static void cpu(Options options) throws Exception { + int cores = Runtime.getRuntime().availableProcessors(); + System.out.println(); + System.out.println("Scenario: cpu | " + n(options.requests()) + " requests at GET /api/cpu, all at the same moment | " + + cores + " CPU cores"); + System.out.println("Each request hashes a value " + n(CPU_ROUNDS) + " times: pure computation, no waiting."); + System.out.println("The application is started twice: once with platform threads, once with virtual threads."); + System.out.println(); + long[] millis = new long[2]; + int[] peaks = new int[2]; + String[] served = new String[2]; + for (int run = 0; run < 2; run++) { + boolean virtual = run == 1; + try (ConfigurableApplicationContext context = Tool.startApplication(List.of("--spring.threads.virtual.enabled=" + virtual)); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + String url = Tool.baseUrl(context) + "/api/cpu?rounds=" + CPU_ROUNDS; + HttpClient http = Tool.httpClient(); + for (int i = 0; i < 2 * cores; i++) { + Tool.send(http, Tool.get(url)); + } + inFlight.reset(); + long startedAt = System.nanoTime(); + List replies = Tool.collect(Tool.fire(http, options.requests(), i -> Tool.get(url), senders)); + millis[run] = (System.nanoTime() - startedAt) / 1_000_000; + peaks[run] = inFlight.peak(); + served[run] = Tool.answers(replies); + } + } + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "", "Platform threads", "Virtual threads"); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "In flight at once (peak)", peaks[0], peaks[1]); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "Answers", served[0], served[1]); + System.out.printf(Locale.ROOT, " %-30s %-22s %s%n", "Time taken", n(millis[0]) + " ms", n(millis[1]) + " ms"); + System.out.println(); + if (millis[1] * 4 >= millis[0] * 3) { + System.out.println("RESULT: NO GAIN. CPU-bound work took " + n(millis[0]) + " ms on platform threads and " + n(millis[1]) + + " ms on virtual threads: both are limited by " + cores + " CPU cores."); + } else { + System.out.println("RESULT: " + n(millis[0]) + " ms on platform threads, " + n(millis[1]) + + " ms on virtual threads. Run it again: with " + cores + " cores the work itself cannot go faster."); + } + System.out.println(); + } + + // ---------------------------------------------------------------- pinning + + private static void pinning() { + int cores = Runtime.getRuntime().availableProcessors(); + int threads = 2 * cores; + long blockMillis = 100; + System.out.println(); + System.out.println("Scenario: pinning | Java " + Runtime.version() + " | " + threads + " virtual threads per case, each blocks for " + + blockMillis + " ms | " + cores + " CPU cores, so " + cores + " carrier threads"); + System.out.println("Pinned: the virtual thread could not unmount while it was blocked, so it held on to its carrier thread."); + System.out.println("Every pinned block is recorded with JFR (event jdk.VirtualThreadPinned), in this JVM."); + System.out.println(); + List results = PinningLab.run(threads, blockMillis); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "Case", "Pinned", "Time", "Why, as JFR reports it"); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "-".repeat(44), "------", "-------", "-".repeat(22)); + boolean synchronizedPins = false; + List stillPins = new ArrayList<>(); + for (PinningLab.Result result : results) { + if (result.unavailable() != null) { + System.out.printf(Locale.ROOT, " %-46s %s%n", result.name(), "skipped: " + result.unavailable()); + continue; + } + List reasons = result.reasons().isEmpty() ? List.of("") : result.reasons(); + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", result.name(), result.pinnedEvents(), + n(result.millis()) + " ms", reasons.getFirst()); + for (String reason : reasons.subList(1, reasons.size())) { + System.out.printf(Locale.ROOT, " %-46s %-8s %-9s %s%n", "", "", "", reason); + } + if (result.pinnedEvents() > 0) { + if (result.name().startsWith("synchronized")) { + synchronizedPins = true; + } else { + stillPins.add(result.name().replace("Thread.sleep ", "blocking ")); + } + } + } + System.out.println(); + if (synchronizedPins) { + System.out.println("RESULT: PINNED. On this JVM a virtual thread that blocks inside synchronized is pinned (Java 21 to 23)."); + } else { + System.out.println("RESULT: synchronized does NOT pin on Java " + Runtime.version().feature() + + " (JEP 491). Still pinned: " + String.join("; ", stillPins) + "."); + } + System.out.println(); + } + + // ---------------------------------------------------------------- options + + private static Options parse(String[] args) { + String scenario = "search"; + int requests = 200; + Boolean virtual = null; + long airlineMillis = 500; + Integer poolSize = null; + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "--help", "-h" -> { + return null; + } + case "--scenario" -> scenario = scenario(value(args, ++i, arg)); + case "--requests" -> requests = number(value(args, ++i, arg), arg, 1, 2_000); + case "--virtual" -> virtual = onOff(value(args, ++i, arg)); + case "--airline-ms" -> airlineMillis = number(value(args, ++i, arg), arg, 0, 60_000); + case "--pool-size" -> poolSize = number(value(args, ++i, arg), arg, 1, 1_000); + default -> throw new IllegalArgumentException("Unknown option: " + arg); + } + } + return new Options(scenario, requests, virtual, airlineMillis, poolSize); + } + + private static String scenario(String value) { + return switch (value) { + case "search", "cpu", "pooled", "pinning" -> value; + default -> throw new IllegalArgumentException("Unknown scenario: " + value + ". Use search, cpu, pooled or pinning."); + }; + } + + private static Boolean onOff(String value) { + return switch (value) { + case "on", "true" -> true; + case "off", "false" -> false; + default -> throw new IllegalArgumentException("--virtual must be on or off, 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 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 search (default): slow searches that wait for the airline and the database"); + System.out.println(" cpu: CPU-bound requests, on platform threads and then on virtual threads"); + System.out.println(" pooled: the same searches, with every airline call handed to a thread pool (exhibit)"); + System.out.println(" pinning: which kinds of blocking pin a virtual thread on this JVM (no database needed)"); + System.out.println(" --requests how many requests to send at the same moment (default: 200)"); + System.out.println(" --virtual on|off virtual threads for this run only (default: what application.properties says)"); + System.out.println(" --airline-ms how long the airline takes to answer (default: 500)"); + System.out.println(" --pool-size database connections in the pool, for this run only (default: application.properties)"); + System.out.println(); + System.out.println("Examples:"); + System.out.println(" ./demo"); + System.out.println(" ./demo --virtual on"); + System.out.println(" ./demo --scenario cpu"); + System.out.println(" ./demo --scenario pinning"); + } + + private Demo() { + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java new file mode 100644 index 0000000..5ea4b9d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Inspect.java @@ -0,0 +1,254 @@ +package com.amigoscode.virtualthreads.demo; + +import static com.amigoscode.virtualthreads.demo.Tool.line; + +import com.amigoscode.virtualthreads.airline.FakeAirline; +import com.amigoscode.virtualthreads.demo.Tool.Reply; +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import java.net.http.HttpClient; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordingStream; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.EnableAsync; + +/** + * Starts the application, sends slow searches at it, and while they are all waiting for the + * airline, looks at the threads: which threads hold the requests, which carrier threads are under + * them, what Tomcat, HikariCP and Postgres see. Then it reports every virtual thread that was + * pinned, from JFR. Run it with ./inspect (or .\inspect on Windows). ./inspect --help lists the flags. + */ +public final class Inspect { + + private static final long AIRLINE_MILLIS = 3_000; + + public static void main(String[] args) throws Exception { + int requests = 50; + Boolean virtual = null; + try { + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "--requests" -> requests = Integer.parseInt(args[++i]); + case "--virtual" -> virtual = switch (args[++i]) { + case "on", "true" -> true; + case "off", "false" -> false; + default -> throw new IllegalArgumentException(); + }; + default -> throw new IllegalArgumentException(); + } + } + if (requests < 1 || requests > 1_000) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException e) { + System.out.println("Usage: ./inspect [--requests ] [--virtual on|off] (Windows: .\\inspect ...)"); + System.out.println(); + System.out.println(" --requests how many slow searches to send at the same moment (default: 50)"); + System.out.println(" --virtual on|off virtual threads for this run only (default: what application.properties says)"); + return; + } + if (!Db.isUp()) { + return; + } + List springArgs = new ArrayList<>(List.of("--airline.delay-ms=" + AIRLINE_MILLIS)); + if (virtual != null) { + springArgs.add("--spring.threads.virtual.enabled=" + virtual); + } + try (ConfigurableApplicationContext context = Tool.startApplication(springArgs, AsyncProbe.class); + ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor()) { + inspect(context, requests, senders); + } + } + + /** Only used by inspect: shows which thread runs an @Async method. Not part of the application. */ + @EnableAsync + public static class AsyncProbe { + + @Async + public CompletableFuture whoRunsMe() { + return CompletableFuture.completedFuture(Thread.currentThread().toString()); + } + } + + private static void inspect(ConfigurableApplicationContext context, int requests, ExecutorService senders) throws Exception { + InFlightRequests inFlight = context.getBean(InFlightRequests.class); + ServerThreads server = context.getBean(ServerThreads.class); + FakeAirline airline = context.getBean(FakeAirline.class); + HikariDataSource dataSource = Tool.hikari(context); + HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); + TaskExecutor taskExecutor = context.getBean("applicationTaskExecutor", TaskExecutor.class); + boolean virtualOn = context.getEnvironment().getProperty("spring.threads.virtual.enabled", Boolean.class, false); + String baseUrl = Tool.baseUrl(context); + HttpClient http = Tool.httpClient(); + + System.out.println(); + System.out.println("SETTINGS"); + line(" spring.threads.virtual.enabled", virtualOn); + line(" Tomcat runs each request on", server.describe()); + line(" @Async and applicationTaskExecutor", describe(taskExecutor)); + line(" HikariCP pool", "at most " + dataSource.getMaximumPoolSize() + " connections, " + + dataSource.getConnectionTimeout() + " ms connection timeout"); + line(" Postgres max_connections", postgres("show max_connections")); + line(" CPU cores (= carrier threads by default)", Runtime.getRuntime().availableProcessors()); + line(" The airline", "answers in " + airline.delayMillis() + " ms (slowed down for inspect), allows " + + airline.maxConcurrentCalls() + " calls at once"); + + List pinned = new CopyOnWriteArrayList<>(); + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", pinned::add); + jfr.startAsync(); + + // A few searches first, so the snapshot does not show startup work. + for (int i = 0; i < 2; i++) { + Tool.send(http, Tool.get(baseUrl + "/api/fares?route=MAN-BCN")); + } + inFlight.reset(); + int tablesBefore = RateTable.timesBuilt(); + List> futures = Tool.fire(http, requests, i -> Tool.get(baseUrl + "/api/fares?route=LHR-JFK"), senders); + + // Wait until every search is either being served or waiting in Tomcat's queue. + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (inFlight.current() + server.queued() < requests && System.nanoTime() < deadline) { + Thread.sleep(10); + } + Thread.sleep(300); + snapshot(requests, inFlight, server, pool); + + List replies = Tool.collect(futures); + System.out.println(); + System.out.println("AFTER ALL " + requests + " SEARCHES WERE ANSWERED"); + line(" Answers", Tool.answers(replies)); + line(" Rate tables built for them", RateTable.timesBuilt() - tablesBefore); + line(" An @Async method ran on", context.getBean(AsyncProbe.class).whoRunsMe().get()); + jfr.stop(); + } + pinningReport(pinned); + System.out.println(); + } + + private static void snapshot(int requests, InFlightRequests inFlight, ServerThreads server, HikariPoolMXBean pool) throws Exception { + List live = inFlight.liveThreads(); + long virtual = live.stream().filter(Thread::isVirtual).count(); + long mounted = live.stream().filter(thread -> InFlightRequests.carrierOf(thread) != null).count(); + System.out.println(); + System.out.println("WHILE " + requests + " SEARCHES WAIT (a snapshot)"); + line(" Requests in flight", inFlight.current()); + line(" Requests waiting in Tomcat's queue", server.queued()); + line(" Threads holding them", virtual + " virtual, " + (live.size() - virtual) + " platform"); + if (virtual > 0) { + line(" Virtual threads mounted on a carrier now", mounted + " of " + virtual); + line(" Carriers they started on", inFlight.carriers().size() + " (" + Tool.some(new ArrayList<>(inFlight.carriers()), 2) + ")"); + } + line(" Platform threads in the whole JVM", ManagementFactory.getThreadMXBean().getThreadCount()); + line(" HikariCP connections", "active " + pool.getActiveConnections() + ", idle " + pool.getIdleConnections() + + ", requests waiting for one " + pool.getThreadsAwaitingConnection()); + line(" Postgres sessions of this app, by state", postgres(""" + select coalesce(string_agg(state || ': ' || n, ', ' order by state), 'none') + from (select state, count(*) as n + from pg_stat_activity + where datname = current_database() and backend_type = 'client backend' + and application_name = 'PostgreSQL JDBC Driver' and pid <> pg_backend_pid() + group by state) s + """)); + System.out.println(); + System.out.println(" Three of the request threads, as Thread.toString() prints them:"); + live.stream().limit(3).forEach(thread -> System.out.println(" " + thread)); + System.out.println(" Where the first one is waiting (top of its stack):"); + if (!live.isEmpty()) { + StackTraceElement[] stack = live.getFirst().getStackTrace(); + List frames = new ArrayList<>(); + for (StackTraceElement frame : stack) { + String text = frame.getClassName() + "." + frame.getMethodName(); + if (frame.getClassName().startsWith("com.amigoscode") || frames.size() < 4) { + frames.add(text); + } + if (frame.getClassName().startsWith("com.amigoscode.virtualthreads.fares.FareController")) { + break; + } + } + frames.forEach(frame -> System.out.println(" " + frame)); + } + } + + private static void pinningReport(List events) { + System.out.println(); + System.out.println("PINNING (JFR event jdk.VirtualThreadPinned, recorded during this run)"); + if (events.isEmpty()) { + System.out.println(" none. No virtual thread was pinned to its carrier while it blocked."); + return; + } + Map byReason = new LinkedHashMap<>(); + for (RecordedEvent event : events) { + String reason = event.hasField("pinnedReason") ? event.getString("pinnedReason") : "(no reason given)"; + byReason.merge(reason + " | at " + firstApplicationFrame(event), 1, Integer::sum); + } + System.out.println(" " + events.size() + " pinned blocks:"); + byReason.forEach((reason, count) -> System.out.println(" " + count + " x " + reason)); + } + + private static String firstApplicationFrame(RecordedEvent event) { + if (event.getStackTrace() == null) { + return "(no stack trace)"; + } + for (RecordedFrame frame : event.getStackTrace().getFrames()) { + String type = frame.getMethod().getType().getName(); + if (!type.startsWith("java.") && !type.startsWith("jdk.") && !type.startsWith("sun.")) { + return type + "." + frame.getMethod().getName(); + } + } + return "(JDK code only)"; + } + + private static String describe(TaskExecutor executor) { + String type = executor.getClass().getSimpleName(); + if (executor instanceof org.springframework.core.task.SimpleAsyncTaskExecutor simple) { + return type + ": a new " + (isVirtual(simple) ? "virtual" : "platform") + " thread for every task" + + (simple.getConcurrencyLimit() > 0 ? ", at most " + simple.getConcurrencyLimit() + " at once" : ", no limit"); + } + if (executor instanceof org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor pool) { + return type + ": a pool of " + pool.getCorePoolSize() + " platform threads" + + (pool.getQueueCapacity() == Integer.MAX_VALUE ? ", unbounded queue" : ", queue of " + pool.getQueueCapacity()); + } + return type; + } + + private static boolean isVirtual(org.springframework.core.task.SimpleAsyncTaskExecutor executor) { + CompletableFuture virtual = new CompletableFuture<>(); + executor.execute(() -> virtual.complete(Thread.currentThread().isVirtual())); + return virtual.join(); + } + + private static String postgres(String sql) { + try (Connection connection = Db.connect(); Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(sql)) { + return result.next() ? result.getString(1) : ""; + } catch (Exception e) { + return "(could not ask Postgres: " + e.getMessage() + ")"; + } + } + + private Inspect() { + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java new file mode 100644 index 0000000..55d7a36 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/demo/Tool.java @@ -0,0 +1,200 @@ +package com.amigoscode.virtualthreads.demo; + +import com.amigoscode.virtualthreads.VirtualThreadsApplication; +import com.zaxxer.hikari.HikariDataSource; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +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.function.IntSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.boot.Banner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +/** What the demo and inspect tools share: starting the application quietly and sending HTTP requests at it. */ +final class Tool { + + /** One answer. Status -1 means the request itself failed (see body). */ + record Reply(int status, String body) { + + String code() { + return status == 200 ? "OK" : json(body, "code"); + } + } + + private Tool() { + } + + /** Starts the real application on a free port, with the logging turned down. */ + static ConfigurableApplicationContext startApplication(List extraArgs, Class... extraSources) { + List> sources = new ArrayList<>(List.of(VirtualThreadsApplication.class)); + sources.addAll(List.of(extraSources)); + SpringApplication app = new SpringApplication(sources.toArray(Class[]::new)); + app.setBannerMode(Banner.Mode.OFF); + app.setLogStartupInfo(false); + List args = new ArrayList<>(List.of( + "--server.port=0", + "--server.shutdown=immediate", + "--logging.level.root=WARN", + // A failed request is counted and shown as one line instead of a full stack trace. + "--logging.level.org.apache.catalina.core.ContainerBase=OFF", + "--logging.level.com.zaxxer.hikari=OFF")); + args.addAll(extraArgs); + return app.run(args.toArray(String[]::new)); + } + + static String baseUrl(ConfigurableApplicationContext context) { + return "http://localhost:" + context.getEnvironment().getProperty("local.server.port"); + } + + /** The demo's own HTTP client. Its helper tasks run on virtual threads, so it adds no platform threads. */ + static HttpClient httpClient() { + return HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(10)) + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + } + + static HttpRequest get(String url) { + return HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(); + } + + /** Starts {@code requests} requests at the same moment and returns without waiting for them. */ + static List> fire(HttpClient http, int requests, IntFunction request, ExecutorService senders) { + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(requests); + for (int i = 0; i < requests; i++) { + int index = i; + futures.add(senders.submit(() -> { + go.await(); + return send(http, request.apply(index)); + })); + } + go.countDown(); + return futures; + } + + static Reply send(HttpClient http, HttpRequest request) { + try { + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + return new Reply(response.statusCode(), response.body()); + } catch (Exception e) { + return new Reply(-1, e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + static List collect(List> futures) throws Exception { + List replies = new ArrayList<>(futures.size()); + for (Future future : futures) { + replies.add(future.get()); + } + return replies; + } + + /** "200 x 200 OK" or "40 x 200 OK, 160 x 503 DB_POOL_TIMEOUT". */ + static String answers(List replies) { + Map counts = new LinkedHashMap<>(); + replies.stream().sorted((a, b) -> Integer.compare(a.status(), b.status())) + .forEach(reply -> counts.merge(reply.status() + " " + reply.code(), 1, Integer::sum)); + List parts = new ArrayList<>(); + counts.forEach((answer, count) -> parts.add(count + " x " + answer)); + return String.join(", ", parts); + } + + static HikariDataSource hikari(ConfigurableApplicationContext context) { + return context.getBean(HikariDataSource.class); + } + + /** The value of one field in a small JSON answer, or null. Good enough for the flat answers of this app. */ + static String json(String body, String field) { + Matcher matcher = Pattern.compile("\"" + field + "\"\\s*:\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|[-0-9.]+|true|false)") + .matcher(body == null ? "" : body); + if (!matcher.find()) { + return null; + } + return matcher.group(2) != null ? matcher.group(2) : matcher.group(1); + } + + /** 20000 -> "20,000". */ + static String n(long number) { + return String.format(Locale.ROOT, "%,d", number); + } + + static void line(String label, Object value) { + System.out.printf(Locale.ROOT, "%-46s %s%n", label, value); + } + + /** Short list for people: "a, b, c ... (20)". */ + static String some(List values, int max) { + List sorted = values.stream().sorted(Tool::naturalOrder).toList(); + if (sorted.size() <= max) { + return String.join(", ", sorted); + } + return String.join(", ", sorted.subList(0, max)) + " ... " + sorted.getLast(); + } + + /** Sorts "exec-2" before "exec-10". */ + private static int naturalOrder(String a, String b) { + String prefixA = a.replaceAll("\\d+$", ""); + String prefixB = b.replaceAll("\\d+$", ""); + if (!prefixA.equals(prefixB) || prefixA.equals(a) || prefixB.equals(b)) { + return a.compareTo(b); + } + return Long.compare(Long.parseLong(a.substring(prefixA.length())), Long.parseLong(b.substring(prefixB.length()))); + } + + /** Looks at a few numbers every 5 ms while something runs, and remembers the highest value of each. */ + static final class Sampler implements AutoCloseable { + + private final Map gauges; + private final Map highest = new ConcurrentHashMap<>(); + private volatile boolean running = true; + private final CompletableFuture done = new CompletableFuture<>(); + + Sampler(Map gauges) { + this.gauges = gauges; + Thread.ofPlatform().daemon().name("demo-sampler").start(() -> { + while (running) { + sample(); + try { + Thread.sleep(5); + } catch (InterruptedException e) { + break; + } + } + sample(); + done.complete(null); + }); + } + + private void sample() { + gauges.forEach((name, gauge) -> highest.merge(name, gauge.getAsInt(), Math::max)); + } + + int highest(String name) { + return highest.getOrDefault(name, 0); + } + + @Override + public void close() { + running = false; + done.join(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java new file mode 100644 index 0000000..e12ad8b --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/exhibit/PooledFareController.java @@ -0,0 +1,70 @@ +package com.amigoscode.virtualthreads.exhibit; + +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * EXHIBIT for Task 6. Do not fix, do not copy. + * + *

The other way people "limit" the calls to the airline: hand every call to a fixed pool of + * fares.max-airline-calls platform threads and wait for the Future. It does cap the airline calls. + * It also brings back everything virtual threads removed: a pool of platform threads sized by + * hand, an unbounded queue in front of it, and a second thread per request (the request thread + * sits parked on Future.get while a pool thread makes the call, so anything the request thread + * carries in a ThreadLocal is not there). Run ./demo --scenario pooled and compare. + */ +@RestController +public class PooledFareController implements DisposableBean { + + private final AirlineClient airline; + private final InFlightRequests inFlight; + private final ExecutorService airlinePool; + + public PooledFareController(AirlineClient airline, InFlightRequests inFlight, + @Value("${fares.max-airline-calls:50}") int poolSize) { + this.airline = airline; + this.inFlight = inFlight; + this.airlinePool = Executors.newFixedThreadPool(poolSize, + Thread.ofPlatform().name("airline-pool-", 1).daemon().factory()); + } + + @GetMapping("/api/fares/pooled") + public Map search(@RequestParam String route) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + Thread requestThread = Thread.currentThread(); + AtomicReference callThread = new AtomicReference<>(); + AirlineQuote quote = airlinePool.submit(() -> { + callThread.set(Thread.currentThread()); + return airline.quote(route); + }).get(); + return Map.of("route", route, "airline", quote.airline(), "priceCents", quote.priceCents(), + "requestThread", requestThread.getName(), "requestThreadVirtual", requestThread.isVirtual(), + "airlineCalledFrom", callThread.get().getName(), "airlineCalledFromVirtual", callThread.get().isVirtual()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted", e); + } catch (ExecutionException e) { + if (e.getCause() instanceof RuntimeException runtime) { + throw runtime; + } + throw new AirlineUnavailableException("The airline call failed", e.getCause()); + } + } + + @Override + public void destroy() { + airlinePool.shutdownNow(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java new file mode 100644 index 0000000..a0140e6 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareController.java @@ -0,0 +1,35 @@ +package com.amigoscode.virtualthreads.fares; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class FareController { + + private final FareService fares; + private final RouteRepository routes; + private final InFlightRequests inFlight; + + public FareController(FareService fares, RouteRepository routes, InFlightRequests inFlight) { + this.fares = fares; + this.routes = routes; + this.inFlight = inFlight; + } + + /** GET /api/fares?route=LHR-JFK¤cy=GBP: slow, it waits for the airline. */ + @GetMapping("/api/fares") + public FareQuote search(@RequestParam String route, @RequestParam(defaultValue = "GBP") String currency) { + try (InFlightRequests.Ticket ignored = inFlight.enter()) { + return fares.search(route, currency); + } + } + + /** GET /api/routes: fast, one small query. Not counted as in flight. */ + @GetMapping("/api/routes") + public List routes() { + return routes.findAll(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java new file mode 100644 index 0000000..5b76f99 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareQuote.java @@ -0,0 +1,10 @@ +package com.amigoscode.virtualthreads.fares; + +import java.math.BigDecimal; + +/** + * The answer to a search. {@code servedBy} and {@code virtual} are not something a real API would + * return: they are here so you can see which thread did the work. + */ +public record FareQuote(String route, String airline, BigDecimal price, String currency, String servedBy, boolean virtual) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java new file mode 100644 index 0000000..eac7634 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/FareService.java @@ -0,0 +1,59 @@ +package com.amigoscode.virtualthreads.fares; + +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.money.ExchangeRates; +import java.math.BigDecimal; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * A fare search: look up the route, ask the airline for a price (slow), convert it into the + * customer's currency, save the search. + */ +@Service +public class FareService { + + private final RouteRepository routes; + private final SearchRepository searches; + private final AirlineClient airline; + private final ExchangeRates rates; + + /** + * TODO Task 5: at most this many calls to the airline at the same time. A search over the limit + * must wait for its turn, not fail, and not be handed to another thread. + */ + private final int maxAirlineCalls; + + public FareService(RouteRepository routes, SearchRepository searches, AirlineClient airline, ExchangeRates rates, + @Value("${fares.max-airline-calls:50}") int maxAirlineCalls) { + this.routes = routes; + this.searches = searches; + this.airline = airline; + this.rates = rates; + this.maxAirlineCalls = maxAirlineCalls; + } + + /** + * TODO Task 4: this transaction takes a database connection at its first statement and keeps it + * until it commits, so every search holds a connection for the whole airline call. With 20 + * Tomcat threads and 20 connections nobody noticed. Do not hold a connection while waiting. + */ + @Transactional + public FareQuote search(String routeCode, String currency) { + Route route = routes.find(routeCode).orElseThrow(() -> new UnknownRouteException(routeCode)); + + AirlineQuote quote = askAirline(route.code()); + + BigDecimal price = rates.fromUsd(quote.priceCents(), currency); + Thread thread = Thread.currentThread(); + FareQuote fare = new FareQuote(route.code(), quote.airline(), price, currency, thread.getName(), thread.isVirtual()); + searches.save(fare); + return fare; + } + + private AirlineQuote askAirline(String route) { + return airline.quote(route); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/Route.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/Route.java new file mode 100644 index 0000000..2b8dbce --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/Route.java @@ -0,0 +1,4 @@ +package com.amigoscode.virtualthreads.fares; + +public record Route(String code, String origin, String destination) { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java new file mode 100644 index 0000000..8f1f5cc --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/RouteRepository.java @@ -0,0 +1,27 @@ +package com.amigoscode.virtualthreads.fares; + +import java.util.List; +import java.util.Optional; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +@Repository +public class RouteRepository { + + private final JdbcTemplate jdbc; + + public RouteRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public Optional find(String code) { + return jdbc.query("select code, origin, destination from route where code = ?", + (rs, row) -> new Route(rs.getString("code"), rs.getString("origin"), rs.getString("destination")), code) + .stream().findFirst(); + } + + public List findAll() { + return jdbc.query("select code, origin, destination from route order by code", + (rs, row) -> new Route(rs.getString("code"), rs.getString("origin"), rs.getString("destination"))); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java new file mode 100644 index 0000000..d32958a --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/SearchRepository.java @@ -0,0 +1,22 @@ +package com.amigoscode.virtualthreads.fares; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +/** Saves every search, with the thread that served it. */ +@Repository +public class SearchRepository { + + private final JdbcTemplate jdbc; + + public SearchRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + public void save(FareQuote quote) { + jdbc.update(""" + insert into fare_search (route, airline, price, currency, served_by, virtual) + values (?, ?, ?, ?, ?, ?) + """, quote.route(), quote.airline(), quote.price(), quote.currency(), quote.servedBy(), quote.virtual()); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java new file mode 100644 index 0000000..b955b03 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/fares/UnknownRouteException.java @@ -0,0 +1,8 @@ +package com.amigoscode.virtualthreads.fares; + +public class UnknownRouteException extends RuntimeException { + + public UnknownRouteException(String route) { + super("Unknown route: " + route); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java new file mode 100644 index 0000000..53460f3 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/ExchangeRates.java @@ -0,0 +1,21 @@ +package com.amigoscode.virtualthreads.money; + +import java.math.BigDecimal; +import org.springframework.stereotype.Component; + +/** + * Converts the airline's price in US dollars into the customer's currency. + */ +@Component +public class ExchangeRates { + + /** + * TODO Task 7: one table per thread, "so it is built once per thread and reused". That held + * while Tomcat reused the same 20 threads. Count the tables built on virtual threads. + */ + private static final ThreadLocal TABLE = ThreadLocal.withInitial(RateTable::build); + + public BigDecimal fromUsd(long usdCents, String currency) { + return TABLE.get().fromUsd(usdCents, currency); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java new file mode 100644 index 0000000..c76ed74 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/RateTable.java @@ -0,0 +1,73 @@ +package com.amigoscode.virtualthreads.money; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Currency; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Exchange rates, precomputed so that a conversion is one array lookup: the rate between every pair + * of 30 currencies for each of the last 90 days. 81,000 numbers, about 650 KB. Building it takes a + * few milliseconds, so it is meant to be built once and reused. + * + *

Read-only once built: every field is final and nothing writes to the array after the + * constructor, so one table can safely be shared by any number of threads. Nothing to change here. + */ +public final class RateTable { + + /** Units of each currency for one US dollar, today. */ + static final List CODES = List.of( + "USD", "GBP", "EUR", "JPY", "CHF", "CAD", "AUD", "NZD", "SEK", "NOK", + "DKK", "PLN", "CZK", "HUF", "RON", "TRY", "ZAR", "INR", "SGD", "HKD", + "CNY", "KRW", "MXN", "BRL", "AED", "SAR", "ILS", "THB", "MYR", "PHP"); + private static final double[] PER_USD = { + 1.00, 0.79, 0.92, 151.00, 0.88, 1.37, 1.52, 1.66, 10.50, 10.70, + 6.87, 3.98, 23.10, 362.00, 4.58, 32.20, 18.40, 83.30, 1.35, 7.82, + 7.24, 1350.00, 17.10, 5.05, 3.67, 3.75, 3.70, 36.40, 4.72, 56.10}; + static final int DAYS = 90; + public static final long BYTES = (long) CODES.size() * CODES.size() * DAYS * Double.BYTES; + + private static final AtomicInteger BUILT = new AtomicInteger(); + + /** [day][from][to], flattened. Day 0 is today. */ + private final double[] rates; + + private RateTable() { + int n = CODES.size(); + double[] table = new double[n * n * DAYS]; + for (int day = 0; day < DAYS; day++) { + // Older days drift a little, so the history is not just 90 copies of today. + double drift = 1.0 + day * 0.0005; + for (int from = 0; from < n; from++) { + for (int to = 0; to < n; to++) { + double rate = PER_USD[to] / PER_USD[from]; + table[(day * n + from) * n + to] = day == 0 ? rate : rate * drift; + } + } + } + this.rates = table; + BUILT.incrementAndGet(); + } + + public static RateTable build() { + return new RateTable(); + } + + /** How many tables have been built since the JVM started. */ + public static int timesBuilt() { + return BUILT.get(); + } + + /** Today's price, in {@code currency}, of {@code usdCents} US cents, rounded to the currency's decimals. */ + public BigDecimal fromUsd(long usdCents, String currency) { + int to = CODES.indexOf(currency); + if (to < 0) { + throw new UnknownCurrencyException(currency); + } + double rate = rates[to]; // day 0, from USD (index 0) + return BigDecimal.valueOf(usdCents, 2) + .multiply(BigDecimal.valueOf(rate)) + .setScale(Currency.getInstance(currency).getDefaultFractionDigits(), RoundingMode.HALF_EVEN); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java new file mode 100644 index 0000000..dc50ef1 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/money/UnknownCurrencyException.java @@ -0,0 +1,8 @@ +package com.amigoscode.virtualthreads.money; + +public class UnknownCurrencyException extends RuntimeException { + + public UnknownCurrencyException(String currency) { + super("Unknown currency: " + currency); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java new file mode 100644 index 0000000..ad62b7c --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/pinning/PinningLab.java @@ -0,0 +1,194 @@ +package com.amigoscode.virtualthreads.pinning; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.ReentrantLock; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordingStream; + +/** + * Which kinds of blocking pin a virtual thread to its carrier, on the JVM you are running. Each + * case starts some virtual threads that all block for the same time, and JFR records every + * jdk.VirtualThreadPinned event while they run. Used by ./demo --scenario pinning. Nothing to + * change here. + */ +public final class PinningLab { + + /** One case: how many pinned events JFR saw, the reasons it gave, and how long the case took. */ + public record Result(String name, int threads, int pinnedEvents, List reasons, long millis, String unavailable) { + } + + private static volatile long callbackSleepMillis; + private static volatile long staticInitSleepMillis; + + private PinningLab() { + } + + public static List run(int threads, long blockMillis) { + warmUp(); + List results = new ArrayList<>(); + results.add(measure("synchronized, Thread.sleep inside", threads, () -> { + Object lock = new Object(); + synchronized (lock) { + sleep(blockMillis); + } + })); + results.add(measure("synchronized, Object.wait inside", threads, () -> { + Object lock = new Object(); + synchronized (lock) { + try { + lock.wait(blockMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + })); + results.add(measure("ReentrantLock, Thread.sleep inside", threads, () -> { + ReentrantLock lock = new ReentrantLock(); + lock.lock(); + try { + sleep(blockMillis); + } finally { + lock.unlock(); + } + })); + staticInitSleepMillis = blockMillis; // not a field of SlowStaticInit: writing one would initialize the class + results.add(measure("Thread.sleep inside a static initializer", threads, SlowStaticInit::touch)); + Optional qsort = qsort(); + if (qsort.isPresent()) { + callbackSleepMillis = blockMillis; + results.add(measure("Thread.sleep in a callback from native code", threads, () -> sortTwoInts(qsort.get()))); + } else { + results.add(new Result("Thread.sleep in a callback from native code", threads, 0, List.of(), 0, + "qsort from the C library is not available on this platform")); + } + return results; + } + + /** The class initializer runs once, on the first thread that touches the class. It blocks. */ + static final class SlowStaticInit { + + static { + sleep(staticInitSleepMillis); + } + + static void touch() { + } + } + + /** Runs {@code task} once on each of {@code threads} virtual threads, all at the same moment, and records pinning. */ + private static Result measure(String name, int threads, Runnable task) { + List events = new CopyOnWriteArrayList<>(); + long millis; + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", events::add); + jfr.startAsync(); + millis = runOnVirtualThreads(threads, task); + jfr.stop(); + } + List reasons = events.stream() + .map(event -> event.hasField("pinnedReason") ? event.getString("pinnedReason") : "(no reason given by this JVM)") + .map(reason -> reason.replace(PinningLab.class.getName() + "$", "")) + .distinct() + .toList(); + return new Result(name, threads, events.size(), reasons, millis, null); + } + + private static long runOnVirtualThreads(int threads, Runnable task) { + CountDownLatch go = new CountDownLatch(1); + long startedAt; + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + for (int i = 0; i < threads; i++) { + executor.submit(() -> { + go.await(); + task.run(); + return null; + }); + } + startedAt = System.nanoTime(); + go.countDown(); + } + return (System.nanoTime() - startedAt) / 1_000_000; + } + + /** + * The first time the JDK runs this code it loads and initializes some of its own classes, and + * that can pin for a moment. Run everything once, unrecorded, so the cases only show themselves. + */ + private static void warmUp() { + Object lock = new Object(); + ReentrantLock reentrantLock = new ReentrantLock(); + runOnVirtualThreads(4, () -> { + synchronized (lock) { + sleep(1); + } + reentrantLock.lock(); + try { + sleep(1); + } finally { + reentrantLock.unlock(); + } + }); + qsort().ifPresent(handle -> { + callbackSleepMillis = 0; + runOnVirtualThreads(2, () -> sortTwoInts(handle)); + }); + } + + private static Optional qsort() { + try { + Linker linker = Linker.nativeLinker(); + return linker.defaultLookup().find("qsort").map(address -> linker.downcallHandle(address, + FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG, ValueLayout.JAVA_LONG, ValueLayout.ADDRESS))); + } catch (RuntimeException e) { + return Optional.empty(); + } + } + + /** Calls C's qsort on two ints. qsort calls back into {@link #compare}, which sleeps. */ + private static void sortTwoInts(MethodHandle qsort) { + try (Arena arena = Arena.ofConfined()) { + Linker linker = Linker.nativeLinker(); + MethodHandle compare = MethodHandles.lookup().findStatic(PinningLab.class, "compare", + MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class)); + MemorySegment callback = linker.upcallStub(compare, FunctionDescriptor.of(ValueLayout.JAVA_INT, + ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT), + ValueLayout.ADDRESS.withTargetLayout(ValueLayout.JAVA_INT)), arena); + MemorySegment numbers = arena.allocateFrom(ValueLayout.JAVA_INT, 2, 1); + qsort.invokeExact(numbers, 2L, ValueLayout.JAVA_INT.byteSize(), callback); + } catch (Throwable e) { + throw new IllegalStateException("Calling qsort failed", e); + } + } + + private static int compare(MemorySegment a, MemorySegment b) { + sleep(callbackSleepMillis); + return Integer.compare(a.get(ValueLayout.JAVA_INT, 0), b.get(ValueLayout.JAVA_INT, 0)); + } + + private static void sleep(long millis) { + if (millis <= 0) { + return; + } + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java new file mode 100644 index 0000000..b1167f4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/InFlightRequests.java @@ -0,0 +1,107 @@ +package com.amigoscode.virtualthreads.threads; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.stereotype.Component; + +/** + * Counts the requests that are being served right now, and remembers which threads served them. + * The controllers call {@link #enter()} first thing and close the ticket last thing, so "in flight" + * means: a thread has picked the request up and is working on it, or waiting inside it. Used by + * the demo, inspect and the tests. Nothing to change here. + */ +@Component +public class InFlightRequests { + + private final AtomicInteger current = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger served = new AtomicInteger(); + private final AtomicInteger virtual = new AtomicInteger(); + private final AtomicInteger platform = new AtomicInteger(); + private final Set threadNames = ConcurrentHashMap.newKeySet(); + private final Set carriers = ConcurrentHashMap.newKeySet(); + private final Set live = ConcurrentHashMap.newKeySet(); + + /** One request. Close it when the request is finished (try-with-resources). */ + public interface Ticket extends AutoCloseable { + @Override + void close(); + } + + public Ticket enter() { + Thread thread = Thread.currentThread(); + int now = current.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + served.incrementAndGet(); + (thread.isVirtual() ? virtual : platform).incrementAndGet(); + threadNames.add(thread.getName()); + String carrier = carrierOf(thread); + if (carrier != null) { + carriers.add(carrier); + } + live.add(thread); + return () -> { + live.remove(thread); + current.decrementAndGet(); + }; + } + + /** + * The carrier a virtual thread is mounted on right now, read from its toString(): + * {@code VirtualThread[#52,tomcat-handler-0]/runnable@ForkJoinPool-1-worker-3}. Null for a + * platform thread, and for a virtual thread that is unmounted (parked) at this moment. + */ + public static String carrierOf(Thread thread) { + String text = thread.toString(); + int at = text.lastIndexOf('@'); + return thread.isVirtual() && at > 0 ? text.substring(at + 1) : null; + } + + /** Requests being served right now. */ + public int current() { + return current.get(); + } + + /** The most requests that were in flight at the same moment since the last reset. */ + public int peak() { + return peak.get(); + } + + public int served() { + return served.get(); + } + + public int servedByVirtualThreads() { + return virtual.get(); + } + + public int servedByPlatformThreads() { + return platform.get(); + } + + /** The names of the threads that served requests since the last reset. */ + public Set threadNames() { + return Set.copyOf(threadNames); + } + + /** The carrier threads the virtual request threads were mounted on when they started. */ + public Set carriers() { + return Set.copyOf(carriers); + } + + /** The threads serving a request right now. */ + public List liveThreads() { + return List.copyOf(live); + } + + public void reset() { + peak.set(current.get()); + served.set(0); + virtual.set(0); + platform.set(0); + threadNames.clear(); + carriers.clear(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java new file mode 100644 index 0000000..d66360f --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/java/com/amigoscode/virtualthreads/threads/ServerThreads.java @@ -0,0 +1,55 @@ +package com.amigoscode.virtualthreads.threads; + +import java.util.concurrent.Executor; +import org.apache.tomcat.util.threads.ThreadPoolExecutor; +import org.springframework.boot.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; +import org.springframework.boot.web.server.context.WebServerApplicationContext; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +/** + * Looks inside Tomcat: which executor runs the requests, and, for a pool of platform threads, how + * many threads it has and how many requests are waiting in its queue. Used by the demo, inspect + * and the tests. Nothing to change here. + */ +@Component +public class ServerThreads { + + private final ApplicationContext context; + + public ServerThreads(ApplicationContext context) { + this.context = context; + } + + /** The executor Tomcat hands every request to. */ + public Executor executor() { + WebServer server = ((WebServerApplicationContext) context).getWebServer(); + return ((TomcatWebServer) server).getTomcat().getConnector().getProtocolHandler().getExecutor(); + } + + /** True when Tomcat starts a new virtual thread for every request. */ + public boolean virtual() { + return !(executor() instanceof ThreadPoolExecutor); + } + + /** Requests Tomcat has read and could not hand to a thread yet: every pooled thread is busy. */ + public int queued() { + return executor() instanceof ThreadPoolExecutor pool ? pool.getQueue().size() : 0; + } + + /** Pooled platform threads that are serving a request right now. 0 for virtual threads. */ + public int busyThreads() { + return executor() instanceof ThreadPoolExecutor pool ? pool.getActiveCount() : 0; + } + + /** One line for people: what kind of executor this is. */ + public String describe() { + Executor executor = executor(); + if (executor instanceof ThreadPoolExecutor pool) { + return "ThreadPoolExecutor: a pool of at most " + pool.getMaximumPoolSize() + + " platform threads, then a queue"; + } + return executor.getClass().getSimpleName() + ": a new virtual thread for every request, no limit"; + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/application.properties b/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/application.properties new file mode 100644 index 0000000..46fa72b --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/application.properties @@ -0,0 +1,29 @@ +spring.application.name=virtual-threads + +# Postgres from compose.yaml. Port 5457 so it does not clash with a Postgres you already run. +spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5457/fares} +spring.datasource.username=${DB_USER:fares} +spring.datasource.password=${DB_PASSWORD:fares} +spring.sql.init.mode=always + +# Tomcat serves each request on one thread. 20 instead of the default 200, so the limit is easy to +# see with a few hundred requests. Do not change it: the tests count on it. +server.tomcat.threads.max=20 + +# TODO Task 2: serve every request on a new virtual thread instead of a pooled platform thread. +spring.threads.virtual.enabled=false + +# The connection pool: one connection for each of Tomcat's 20 threads (the HikariCP default is 10). +# A request that cannot get a connection within 2 seconds fails. The default is 30 seconds; most +# teams set a few seconds, so that a request fails fast instead of hanging. +spring.datasource.hikari.maximum-pool-size=20 +spring.datasource.hikari.connection-timeout=2000 + +# How many airline calls this application makes at the same time, at most (Task 5). +fares.max-airline-calls=50 + +# The airline. In this project it is a small fake HTTP server inside the application (see +# FakeAirline): it answers after airline.delay-ms, and refuses with 429 Too Many Requests when more +# than airline.max-concurrent-calls calls are in progress at once. +airline.delay-ms=500 +airline.max-concurrent-calls=50 diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/schema.sql b/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/schema.sql new file mode 100644 index 0000000..9f773cd --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/main/resources/schema.sql @@ -0,0 +1,27 @@ +-- Runs on every start (spring.sql.init.mode=always). + +create table if not exists route ( + code varchar(7) primary key, + origin varchar(60) not null, + destination varchar(60) not null +); + +insert into route (code, origin, destination) values + ('LHR-JFK', 'London Heathrow', 'New York JFK'), + ('LHR-CDG', 'London Heathrow', 'Paris Charles de Gaulle'), + ('MAN-BCN', 'Manchester', 'Barcelona'), + ('LGW-LIS', 'London Gatwick', 'Lisbon'), + ('EDI-AMS', 'Edinburgh', 'Amsterdam') +on conflict (code) do nothing; + +-- One row per search: what was found, and which thread served the request. +create table if not exists fare_search ( + id bigserial primary key, + route varchar(7) not null references route (code), + airline varchar(60) not null, + price numeric(12, 2) not null, + currency char(3) not null, + served_by varchar(200) not null, + virtual boolean not null, + searched_at timestamptz not null default now() +); diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java new file mode 100644 index 0000000..1b8fec9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/AirlineLimitIT.java @@ -0,0 +1,85 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.IntegrationTest; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.TestPropertySource; + +/** + * Task 5. Virtual threads on. The airline allows 5 calls at once (the stub refuses the 6th, like the + * real one answers 429), and the application is configured with fares.max-airline-calls=5. + */ +@Tag("task5") +@TestPropertySource(properties = {"spring.threads.virtual.enabled=true", "fares.max-airline-calls=5"}) +class AirlineLimitIT extends IntegrationTest { + + private static final int LIMIT = 5; + private static final int SEARCHES = 15; + + @BeforeEach + void theAirlineAllowsFive() { + airline.refuseAbove(LIMIT); + } + + @Test + @DisplayName("Airline limit: 15 searches at once, the airline allows 5: it never has more than 5 calls in progress") + void neverMoreThanFiveAtTheAirline() { + sendFifteenAndRelease(); + + assertThat(airline.peak()) + .withFailMessage("The airline had %d calls in progress at the same moment. It allows %d.", airline.peak(), LIMIT) + .isLessThanOrEqualTo(LIMIT); + } + + @Test + @DisplayName("Airline limit: all 15 get a fare. A search over the limit waits for a free slot instead of failing") + void everySearchGetsAFare() { + List replies = sendFifteenAndRelease(); + + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + } + + @Test + @DisplayName("Airline limit: the airline is called on the request's own virtual thread, not handed to a thread pool") + void calledOnTheRequestThread() { + for (int i = 0; i < 3; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + assertThat(airline.fromOtherThreads()).as("airline calls made by a thread that is not the request's thread").isZero(); + assertThat(airline.fromVirtualThreads()).as("airline calls made from a virtual thread").isEqualTo(3); + } + + @Test + @DisplayName("Airline limit: a failed airline call gives its slot back. After 5 failures in a row, the next 5 searches still get a fare") + void aFailedCallGivesItsSlotBack() { + airline.failNext(LIMIT); + for (int i = 0; i < LIMIT; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(10)).status()).as("a search while the airline is down").isEqualTo(502); + } + + List replies = Searches.start(port, LIMIT, Searches.SEARCH, Duration.ofSeconds(10)).finish(); + + assertThat(Searches.failures(replies)).as("searches after the airline came back").isEmpty(); + } + + /** + * Sends 15 searches and holds the airline until either all 15 got there (nothing limits them), or + * exactly 5 got there and the other 10 are in flight and stay where they are: waiting for a slot. + */ + private List sendFifteenAndRelease() { + airline.holdEveryCall(); + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(300), () -> airline.arrivals() == SEARCHES + || (airline.arrivals() == LIMIT && inFlight.current() == SEARCHES)); + airline.release(); + return searches.finish(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java new file mode 100644 index 0000000..f1da300 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/CarrierThreadsTest.java @@ -0,0 +1,74 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 3. Plain Java, no Spring: what the JVM does with a virtual thread that blocks. These tests + * pass from the start. They document what ./inspect shows you. + */ +@Tag("task3") +class CarrierThreadsTest { + + private static final int THREADS = 1_000; + + private final CountDownLatch gate = new CountDownLatch(1); + private final Set carriers = ConcurrentHashMap.newKeySet(); + private final List threads = new ArrayList<>(); + + @BeforeEach + void startThousandBlockedVirtualThreads() { + // Once unrecorded, so the JDK has loaded the classes it needs before we look. + Thread.ofVirtual().start(() -> InFlightRequests.carrierOf(Thread.currentThread())); + for (int i = 0; i < THREADS; i++) { + threads.add(Thread.ofVirtual().name("blocked-", i).start(() -> { + carriers.add(InFlightRequests.carrierOf(Thread.currentThread())); + try { + gate.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + })); + } + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)) + .until(() -> threads.stream().allMatch(thread -> thread.getState() == Thread.State.WAITING)); + } + + @AfterEach + void releaseThem() throws InterruptedException { + gate.countDown(); + for (Thread thread : threads) { + thread.join(); + } + } + + @Test + @DisplayName("Unmount: 1,000 virtual threads are blocked at the same moment, and not one of them is holding a carrier thread") + void blockedVirtualThreadsAreUnmounted() { + List mounted = threads.stream().filter(thread -> InFlightRequests.carrierOf(thread) != null) + .map(Thread::toString).toList(); + + assertThat(mounted).as("blocked virtual threads that are still mounted on a carrier").isEmpty(); + assertThat(threads.getFirst().toString()).as("a blocked virtual thread, as toString() prints it").endsWith("/waiting"); + } + + @Test + @DisplayName("Carriers: those 1,000 virtual threads ran on a handful of carrier threads (about one per CPU core), not on 1,000 OS threads") + void aHandfulOfCarriers() { + assertThat(carriers).as("carrier threads").allSatisfy(carrier -> assertThat(carrier).startsWith("ForkJoinPool")); + assertThat(carriers.size()).as("carrier threads used by %d virtual threads", THREADS).isLessThan(THREADS / 10); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/Check.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/Check.java new file mode 100644 index 0000000..e1c05de --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/Check.java @@ -0,0 +1,119 @@ +package com.amigoscode.virtualthreads; + +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. Task 6 is an inspection task: you answer questions, no code. Tasks 1, 3 + * and 8 are inspection tasks too, and their tests pass from the start: they document what you see. + */ + 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 thread-per-request ceiling"); + TASKS.put("2", "Task 2: Turn on virtual threads"); + TASKS.put("3", "Task 3: Inspect virtual threads: carriers, mount and unmount"); + TASKS.put("4", "Task 4: Fix the new bottleneck: the connection pool"); + TASKS.put("5", "Task 5: Limit the airline calls with a Semaphore, not a thread pool"); + TASKS.put("7", "Task 7: Fix the ThreadLocal cache"); + TASKS.put("8", "Task 8: Inspect pinning on Java 25"); + } + + 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/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java new file mode 100644 index 0000000..4f66b61 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ConnectionPoolIT.java @@ -0,0 +1,69 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.OnVirtualThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 4. Virtual threads on, a pool of 10 connections that gives up after 500 ms. The airline stub + * holds every call at a gate. The test waits until every search has either reached the airline or + * already failed, then looks. + */ +@Tag("task4") +class ConnectionPoolIT extends OnVirtualThreads { + + private static final int SEARCHES = 30; + + @Test + @DisplayName("Pool: while 30 searches wait for the airline, none of them is holding a database connection") + void noConnectionHeldWhileWaitingForTheAirline() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntil(() -> airline.arrivals() + searches.failed() == SEARCHES); + int held = pool().getActiveConnections(); + int atTheAirline = airline.arrivals(); + + airline.release(); + searches.finish(); + assertThat(held) + .withFailMessage("%d of the pool's 10 connections were held by the %d searches that were waiting for the airline.", + held, atTheAirline) + .isZero(); + } + + @Test + @DisplayName("Pool: 30 searches at the same moment, a pool of 10 connections: every search gets a fare, none times out waiting for a connection") + void nobodyTimesOutWaitingForAConnection() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntil(() -> airline.arrivals() + searches.failed() == SEARCHES); + + airline.release(); + List replies = searches.finish(); + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + } + + @Test + @DisplayName("Pool: every search is still saved, with its price and the thread that served it") + void everySearchIsSaved() { + Searches.Reply reply = Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)); + + assertThat(reply.status()).as("answer to the search: " + reply.body()).isEqualTo(200); + List> rows = jdbc.queryForList("select route, airline, price, currency, served_by, virtual from fare_search"); + assertThat(rows).as("rows in fare_search").hasSize(1); + assertThat(rows.getFirst().get("route")).isEqualTo("LHR-JFK"); + assertThat(rows.getFirst().get("price").toString()).as("price of 412.50 US dollars in pounds").isEqualTo("325.88"); + assertThat(rows.getFirst().get("currency")).isEqualTo("GBP"); + assertThat(reply.body()).contains("\"servedBy\":\"" + rows.getFirst().get("served_by") + "\""); + assertThat(rows.getFirst().get("virtual")).isEqualTo(true); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java new file mode 100644 index 0000000..5130c6a --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/ExchangeRatesTest.java @@ -0,0 +1,35 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.amigoscode.virtualthreads.money.ExchangeRates; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import java.math.BigDecimal; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Unit tests: whatever you change about how the table is kept, the conversions stay right. */ +@Tag("task7") +class ExchangeRatesTest { + + @Test + @DisplayName("Rates: 100.00 US dollars is 79.00 pounds, 92.00 euros and 15100 yen, also from 100 virtual threads at once") + void convertsFromAnyThread() throws Exception { + ExchangeRates rates = new ExchangeRates(); + List>> results; + try (ExecutorService threads = Executors.newVirtualThreadPerTaskExecutor()) { + results = threads.invokeAll(java.util.Collections.nCopies(100, () -> List.of( + rates.fromUsd(10_000, "GBP"), rates.fromUsd(10_000, "EUR"), rates.fromUsd(10_000, "JPY")))); + } + for (Future> result : results) { + assertThat(result.get()).containsExactly(new BigDecimal("79.00"), new BigDecimal("92.00"), new BigDecimal("15100")); + } + assertThatThrownBy(() -> rates.fromUsd(10_000, "XYZ")).isInstanceOf(UnknownCurrencyException.class); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java new file mode 100644 index 0000000..07769b4 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/FareControllerTest.java @@ -0,0 +1,98 @@ +package com.amigoscode.virtualthreads; + +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.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.fares.FareController; +import com.amigoscode.virtualthreads.fares.FareQuote; +import com.amigoscode.virtualthreads.fares.FareService; +import com.amigoscode.virtualthreads.fares.UnknownRouteException; +import com.amigoscode.virtualthreads.money.UnknownCurrencyException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.math.BigDecimal; +import java.sql.SQLTransientConnectionException; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.CannotCreateTransactionException; + +/** + * Unit tests for the HTTP contract: no Spring context, no database, FareService is a stub. They pass + * from the start and must keep passing: whatever you change, a search that cannot be served gets a + * clear error, never a 500. + */ +@Tag("baseline") +class FareControllerTest { + + @Test + @DisplayName("HTTP: a search returns 200 with the route, the airline, the price and the thread that served it") + void searchReturnsTheFare() throws Exception { + api(() -> new FareQuote("LHR-JFK", "Skyway", new BigDecimal("325.88"), "GBP", "tomcat-handler-7", true)) + .perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.route").value("LHR-JFK")) + .andExpect(jsonPath("$.price").value(325.88)) + .andExpect(jsonPath("$.currency").value("GBP")) + .andExpect(jsonPath("$.servedBy").value("tomcat-handler-7")) + .andExpect(jsonPath("$.virtual").value(true)); + } + + @Test + @DisplayName("HTTP: an unknown route returns 404 UNKNOWN_ROUTE") + void unknownRouteReturnsNotFound() throws Exception { + api(() -> { + throw new UnknownRouteException("XXX-YYY"); + }).perform(get("/api/fares?route=XXX-YYY")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.code").value("UNKNOWN_ROUTE")); + } + + @Test + @DisplayName("HTTP: an unknown currency returns 400 UNKNOWN_CURRENCY") + void unknownCurrencyReturnsBadRequest() throws Exception { + api(() -> { + throw new UnknownCurrencyException("XYZ"); + }).perform(get("/api/fares?route=LHR-JFK¤cy=XYZ")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("UNKNOWN_CURRENCY")); + } + + @Test + @DisplayName("HTTP: the airline refusing the call (429 Too Many Requests) returns 503 AIRLINE_BUSY") + void airlineBusyReturnsServiceUnavailable() throws Exception { + api(() -> { + throw new AirlineBusyException("The airline answered 429 Too Many Requests for LHR-JFK"); + }).perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.code").value("AIRLINE_BUSY")); + } + + @Test + @DisplayName("HTTP: no database connection within the timeout returns 503 DB_POOL_TIMEOUT, not a 500") + void poolTimeoutReturnsServiceUnavailable() throws Exception { + api(() -> { + throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", + new SQLTransientConnectionException("HikariPool-1 - Connection is not available, request timed out after 2000ms")); + }).perform(get("/api/fares?route=LHR-JFK")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.code").value("DB_POOL_TIMEOUT")); + } + + /** The controller wired to a FareService whose search does whatever the test says. */ + private static MockMvc api(Supplier search) { + FareService stub = new FareService(null, null, null, null, 50) { + @Override + public FareQuote search(String route, String currency) { + return search.get(); + } + }; + return MockMvcBuilders.standaloneSetup(new FareController(stub, null, new InFlightRequests())) + .setControllerAdvice(new ApiExceptionHandler()) + .build(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PinningTest.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PinningTest.java new file mode 100644 index 0000000..c3590ba --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PinningTest.java @@ -0,0 +1,182 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordingStream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 8. Plain Java, no Spring. JFR records a jdk.VirtualThreadPinned event every time a virtual + * thread blocks while it cannot unmount. These tests record those events in this JVM while a virtual + * thread blocks in different ways. They pass from the start: they document Java 25. + */ +@Tag("task8") +class PinningTest { + + private static final Object LOCK = new Object(); + + /** Not a field of SlowToInitialize: reading one from the test thread would wait for its initializer. */ + private static final CountDownLatch STATIC_INIT_GATE = new CountDownLatch(1); + + @Test + @DisplayName("Java 25: a virtual thread that blocks inside synchronized is not pinned (JEP 491, since Java 24)") + void synchronizedDoesNotPin() throws Exception { + CountDownLatch gate = new CountDownLatch(1); + Runnable blockInsideSynchronized = () -> { + synchronized (LOCK) { + block(gate); + } + }; + warmUp(); + + List pinned = record(() -> { + Thread holder = Thread.ofVirtual().start(blockInsideSynchronized); + Thread waiter = Thread.ofVirtual().start(blockInsideSynchronized); // has to wait for the monitor + waitUntilBlocked(holder, waiter); + gate.countDown(); + join(holder, waiter); + }); + + assertThat(pinned).as("pinned events while two virtual threads block inside and in front of synchronized").isEmpty(); + } + + @Test + @DisplayName("Java 25: Object.wait() inside synchronized does not pin either") + void objectWaitDoesNotPin() throws Exception { + Object monitor = new Object(); + boolean[] ready = {false}; + Runnable waitForReady = () -> { + synchronized (monitor) { + while (!ready[0]) { + try { + monitor.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + }; + + List pinned = record(() -> { + Thread waiter = Thread.ofVirtual().start(waitForReady); + waitUntilBlocked(waiter); + synchronized (monitor) { + ready[0] = true; + monitor.notifyAll(); + } + join(waiter); + }); + + assertThat(pinned).as("pinned events while a virtual thread waits in Object.wait()").isEmpty(); + } + + @Test + @DisplayName("Java 25: a virtual thread that blocks inside a static initializer is still pinned") + void blockingInAStaticInitializerPins() throws Exception { + List pinned = record(() -> { + Thread first = Thread.ofVirtual().start(SlowToInitialize::touch); + waitUntilBlocked(first); + STATIC_INIT_GATE.countDown(); + join(first); + }); + + assertThat(pinned).as("pinned events while a virtual thread blocks in a static initializer").isNotEmpty(); + assertThat(pinned.getFirst().getString("pinnedReason")).as("the reason JFR gives").contains(""); + } + + /** Its static initializer blocks until the test opens the gate. Used by one test only: a class is initialized once. */ + static final class SlowToInitialize { + + static { + PinningTest.block(STATIC_INIT_GATE); + } + + static void touch() { + } + } + + /** Records the jdk.VirtualThreadPinned events of this test class's threads while {@code work} runs. */ + private static List record(ThrowingRunnable work) throws Exception { + List events = new CopyOnWriteArrayList<>(); + try (RecordingStream jfr = new RecordingStream()) { + jfr.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO).withStackTrace(); + jfr.onEvent("jdk.VirtualThreadPinned", events::add); + jfr.startAsync(); + work.run(); + jfr.stop(); + } + return events.stream().filter(PinningTest::fromThisTest).toList(); + } + + private static boolean fromThisTest(RecordedEvent event) { + if (event.getStackTrace() == null) { + return false; + } + for (RecordedFrame frame : event.getStackTrace().getFrames()) { + if (frame.getMethod().getType().getName().startsWith(PinningTest.class.getName())) { + return true; + } + } + return false; + } + + /** + * The same thing once, unrecorded, on another lock. The first time, the JDK loads and initializes + * classes it needs for this (and that can pin for a moment), so we only look at the second time. + */ + private static void warmUp() throws InterruptedException { + Object lock = new Object(); + CountDownLatch gate = new CountDownLatch(1); + Runnable blockInsideSynchronized = () -> { + synchronized (lock) { + block(gate); + } + }; + Thread holder = Thread.ofVirtual().start(blockInsideSynchronized); + Thread waiter = Thread.ofVirtual().start(blockInsideSynchronized); + waitUntilBlocked(holder, waiter); + gate.countDown(); + join(holder, waiter); + } + + private static void waitUntilBlocked(Thread... threads) { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(5)).until(() -> { + for (Thread thread : threads) { + Thread.State state = thread.getState(); + if (state != Thread.State.WAITING && state != Thread.State.BLOCKED && state != Thread.State.TIMED_WAITING) { + return false; + } + } + return true; + }); + } + + private static void join(Thread... threads) throws InterruptedException { + for (Thread thread : threads) { + thread.join(Duration.ofSeconds(10)); + } + } + + static void block(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run() throws Exception; + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java new file mode 100644 index 0000000..db9c214 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/PlatformThreadsIT.java @@ -0,0 +1,56 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.OnPlatformThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 1. These tests pass on purpose: they pin down the thread-per-request ceiling. The airline + * stub holds every call at a gate, so the test decides when the slow call ends. Nothing is left to + * timing: the test waits until every request is either being served or queued, then counts. + */ +@Tag("task1") +class PlatformThreadsIT extends OnPlatformThreads { + + @Test + @DisplayName("Platform threads: 30 slow searches, Tomcat has 20 threads: 20 are in flight, the other 10 wait in Tomcat's queue") + void twentyInFlightTenQueued() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, 30); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == 30); + + assertThat(inFlight.current()).as("searches in flight").isEqualTo(20); + assertThat(server.queued()).as("searches waiting in Tomcat's queue").isEqualTo(10); + + airline.release(); + List replies = searches.finish(); + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + assertThat(inFlight.peak()).as("most searches in flight at the same moment").isEqualTo(20); + } + + @Test + @DisplayName("Platform threads: while all 20 threads wait for the airline, even a fast GET /api/routes waits in the same queue") + void aFastRequestWaitsBehindTheSlowOnes() { + airline.holdEveryCall(); + Searches searches = Searches.start(port, 30); + waitUntil(() -> inFlight.current() == 20 && server.queued() == 10); + + CompletableFuture routes = CompletableFuture.supplyAsync( + () -> Searches.send(port, "/api/routes", Duration.ofSeconds(30))); + waitUntil(() -> server.queued() == 11); + + assertThat(routes).as("GET /api/routes, while every Tomcat thread is waiting for the airline").isNotDone(); + + airline.release(); + assertThat(routes.join().status()).as("GET /api/routes once the threads are free").isEqualTo(200); + searches.finish(); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java new file mode 100644 index 0000000..f9eb9db --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnPlatformThreadsIT.java @@ -0,0 +1,27 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.support.OnPlatformThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Why the ThreadLocal looked fine for years: pooled threads are reused. Passes from the start. */ +@Tag("task7") +class RateTableOnPlatformThreadsIT extends OnPlatformThreads { + + @Test + @DisplayName("ThreadLocal: on a pool of 20 platform threads, 50 searches build the rate table at most 20 times (why it looked fine)") + void builtAtMostOncePerPooledThread() { + int before = RateTable.timesBuilt(); + + List replies = Searches.start(port, 50).finish(); + + assertThat(Searches.failures(replies)).as("failed searches").isEmpty(); + assertThat(RateTable.timesBuilt() - before).as("rate tables built by 50 searches on 20 pooled threads").isLessThanOrEqualTo(20); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java new file mode 100644 index 0000000..3a53b84 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/RateTableOnVirtualThreadsIT.java @@ -0,0 +1,32 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.money.RateTable; +import com.amigoscode.virtualthreads.support.OnVirtualThreads; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** Task 7. Every search converts the airline's price with the rate table. How often is it built? */ +@Tag("task7") +class RateTableOnVirtualThreadsIT extends OnVirtualThreads { + + @Test + @DisplayName("ThreadLocal: 20 searches on virtual threads build the rate table at most once, not once per request") + void builtAtMostOnce() { + int before = RateTable.timesBuilt(); + + for (int i = 0; i < 20; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + int built = RateTable.timesBuilt() - before; + assertThat(built) + .withFailMessage("20 searches built the rate table %d times (%,d KB). Each virtual thread serves one request," + + " so a ThreadLocal is never reused.", built, built * RateTable.BYTES / 1024) + .isLessThanOrEqualTo(1); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java new file mode 100644 index 0000000..ef71663 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/VirtualThreadsIT.java @@ -0,0 +1,72 @@ +package com.amigoscode.virtualthreads; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.amigoscode.virtualthreads.support.IntegrationTest; +import com.amigoscode.virtualthreads.support.Searches; +import java.time.Duration; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Task 2. The application exactly as application.properties configures it. The airline stub holds + * every call at a gate; the test waits until every request is either being served or queued in + * Tomcat, then counts. + */ +@Tag("task2") +class VirtualThreadsIT extends IntegrationTest { + + private static final int SEARCHES = 50; + + @Test + @DisplayName("Virtual threads: 50 slow searches are all in flight at the same moment. Tomcat's limit of 20 threads no longer applies") + void allFiftyInFlight() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == SEARCHES); + int inFlightNow = inFlight.current(); + int queuedNow = server.queued(); + + airline.release(); + searches.finish(); + assertThat(inFlightNow) + .withFailMessage("Only %d of %d searches were in flight; %d waited in Tomcat's queue for a free thread.", + inFlightNow, SEARCHES, queuedNow) + .isEqualTo(SEARCHES); + } + + @Test + @DisplayName("Virtual threads: every request is served by a virtual thread") + void servedByVirtualThreads() { + for (int i = 0; i < 5; i++) { + assertThat(Searches.send(port, Searches.SEARCH, Duration.ofSeconds(30)).status()).isEqualTo(200); + } + + assertThat(inFlight.servedByPlatformThreads()) + .withFailMessage("%d of 5 requests were served by platform threads: %s", + inFlight.servedByPlatformThreads(), inFlight.threadNames()) + .isZero(); + assertThat(inFlight.servedByVirtualThreads()).as("requests served by virtual threads").isEqualTo(5); + } + + @Test + @DisplayName("Virtual threads: the 50 request threads run on a few carrier threads, platform threads of a ForkJoinPool, fewer than 50") + void aFewCarrierThreads() { + airline.holdEveryCall(); + + Searches searches = Searches.start(port, SEARCHES); + waitUntilSteady(Duration.ofMillis(200), () -> inFlight.current() + server.queued() == SEARCHES); + airline.release(); + searches.finish(); + + Set carriers = inFlight.carriers(); + assertThat(carriers) + .withFailMessage("No carrier threads: the requests were served by platform threads, which run on their own OS thread.") + .isNotEmpty(); + assertThat(carriers).as("carrier threads").allSatisfy(carrier -> assertThat(carrier).startsWith("ForkJoinPool")); + assertThat(carriers.size()).as("carrier threads under %d virtual threads", SEARCHES).isLessThan(SEARCHES); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java new file mode 100644 index 0000000..9d1dd1d --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/ControllableAirline.java @@ -0,0 +1,122 @@ +package com.amigoscode.virtualthreads.support; + +import com.amigoscode.virtualthreads.airline.AirlineBusyException; +import com.amigoscode.virtualthreads.airline.AirlineClient; +import com.amigoscode.virtualthreads.airline.AirlineQuote; +import com.amigoscode.virtualthreads.airline.AirlineUnavailableException; +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Replaces the airline in the integration tests. Instead of sleeping, every call can be held at a + * gate until the test releases it, so a test decides exactly when the "slow" call ends, and can + * count how many callers are inside at the same moment. It can also behave like the real airline's + * rate limit, and fail on purpose. + */ +public class ControllableAirline implements AirlineClient { + + public static final long PRICE_CENTS = 41_250; + + private final InFlightRequests inFlight; + + private final AtomicInteger arrivals = new AtomicInteger(); + private final AtomicInteger inProgress = new AtomicInteger(); + private final AtomicInteger peak = new AtomicInteger(); + private final AtomicInteger fromVirtualThreads = new AtomicInteger(); + private final AtomicInteger fromOtherThreads = new AtomicInteger(); + private final AtomicInteger failuresLeft = new AtomicInteger(); + private volatile int refuseAbove; + private volatile CountDownLatch gate; + + public ControllableAirline(InFlightRequests inFlight) { + this.inFlight = inFlight; + } + + public void reset() { + release(); + arrivals.set(0); + peak.set(0); + fromVirtualThreads.set(0); + fromOtherThreads.set(0); + failuresLeft.set(0); + refuseAbove = 0; + gate = null; + } + + /** Every call waits at the gate until {@link #release()}. */ + public void holdEveryCall() { + gate = new CountDownLatch(1); + } + + public void release() { + CountDownLatch current = gate; + if (current != null) { + current.countDown(); + } + } + + /** Like the real airline: a call that finds more than {@code limit} calls in progress is refused (429). */ + public void refuseAbove(int limit) { + refuseAbove = limit; + } + + /** The next {@code calls} calls fail straight away, as if the airline were down. */ + public void failNext(int calls) { + failuresLeft.set(calls); + } + + /** Calls that reached the airline since the last reset. */ + public int arrivals() { + return arrivals.get(); + } + + /** The most calls that were in progress at the same moment. */ + public int peak() { + return peak.get(); + } + + public int fromVirtualThreads() { + return fromVirtualThreads.get(); + } + + /** Calls made by a thread that is not the thread serving the request. */ + public int fromOtherThreads() { + return fromOtherThreads.get(); + } + + @Override + public AirlineQuote quote(String route) { + if (failuresLeft.getAndDecrement() > 0) { + throw new AirlineUnavailableException("The airline is down (a failure the test asked for)"); + } + Thread caller = Thread.currentThread(); + if (caller.isVirtual()) { + fromVirtualThreads.incrementAndGet(); + } + if (!inFlight.liveThreads().contains(caller)) { + fromOtherThreads.incrementAndGet(); + } + arrivals.incrementAndGet(); + int now = inProgress.incrementAndGet(); + peak.accumulateAndGet(now, Math::max); + try { + boolean tooMany = refuseAbove > 0 && now > refuseAbove; + CountDownLatch current = gate; + if (current != null && !current.await(30, TimeUnit.SECONDS)) { + throw new AirlineUnavailableException("The test never released the airline gate"); + } + if (tooMany) { + throw new AirlineBusyException("The airline answered 429 Too Many Requests: " + now + + " calls were in progress, it allows " + refuseAbove); + } + return new AirlineQuote("Skyway", PRICE_CENTS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AirlineUnavailableException("Interrupted", e); + } finally { + inProgress.decrementAndGet(); + } + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java new file mode 100644 index 0000000..a9453e8 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/IntegrationTest.java @@ -0,0 +1,103 @@ +package com.amigoscode.virtualthreads.support; + +import static org.awaitility.Awaitility.await; + +import com.amigoscode.virtualthreads.threads.InFlightRequests; +import com.amigoscode.virtualthreads.threads.ServerThreads; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.time.Duration; +import java.util.concurrent.Callable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +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 start the real application, with Tomcat on a free port, against + * a real Postgres started by Testcontainers (Docker must be running). Only the airline is replaced, + * by a stub the tests control. The threads, Tomcat's executor and the connection pool are the real + * ones: that is what these tests are about. One Postgres container is shared by every test class. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = "spring.main.banner-mode=off") +@Import(IntegrationTest.TestBeans.class) +public abstract class IntegrationTest { + + // Several test classes run with different settings, so several applications (and pools) are open at once. + private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine") + .withCommand("postgres", "-c", "max_connections=200"); + + 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 + ControllableAirline controllableAirline(InFlightRequests inFlight) { + return new ControllableAirline(inFlight); + } + } + + @Value("${local.server.port}") + protected int port; + + @Autowired + protected ControllableAirline airline; + + @Autowired + protected InFlightRequests inFlight; + + @Autowired + protected ServerThreads server; + + @Autowired + protected JdbcTemplate jdbc; + + @Autowired + private HikariDataSource dataSource; + + @BeforeEach + void cleanState() { + airline.reset(); + inFlight.reset(); + jdbc.execute("truncate table fare_search restart identity"); + } + + @AfterEach + void letEveryoneGo() { + airline.release(); + } + + protected HikariPoolMXBean pool() { + return dataSource.getHikariPoolMXBean(); + } + + /** Waits until {@code condition} is true. Not a timing assertion: it only decides when to look. */ + protected static void waitUntil(Callable condition) { + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)).until(condition); + } + + /** Waits until {@code condition} has been true, without a break, for {@code steady}. */ + protected static void waitUntilSteady(Duration steady, Callable condition) { + await().atMost(Duration.ofSeconds(20)).pollInterval(Duration.ofMillis(10)).during(steady).until(condition); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java new file mode 100644 index 0000000..98a99d9 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnPlatformThreads.java @@ -0,0 +1,14 @@ +package com.amigoscode.virtualthreads.support; + +import org.springframework.test.context.TestPropertySource; + +/** + * The application as it was before virtual threads, whatever application.properties says: Tomcat's + * pool of 20 platform threads. The connection timeout is long, so nothing times out while a test + * holds every thread on purpose. + */ +@TestPropertySource(properties = { + "spring.threads.virtual.enabled=false", + "spring.datasource.hikari.connection-timeout=30000"}) +public abstract class OnPlatformThreads extends IntegrationTest { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java new file mode 100644 index 0000000..0b810de --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/OnVirtualThreads.java @@ -0,0 +1,15 @@ +package com.amigoscode.virtualthreads.support; + +import org.springframework.test.context.TestPropertySource; + +/** + * Virtual threads on, whatever application.properties says, with a small connection pool (10) that + * gives up quickly (500 ms), and no limit on airline calls that a test could run into. + */ +@TestPropertySource(properties = { + "spring.threads.virtual.enabled=true", + "spring.datasource.hikari.maximum-pool-size=10", + "spring.datasource.hikari.connection-timeout=500", + "fares.max-airline-calls=100"}) +public abstract class OnVirtualThreads extends IntegrationTest { +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/Searches.java b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/Searches.java new file mode 100644 index 0000000..522be63 --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/java/com/amigoscode/virtualthreads/support/Searches.java @@ -0,0 +1,101 @@ +package com.amigoscode.virtualthreads.support; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +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.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** Sends HTTP requests at the running application, all at the same moment, like many customers would. */ +public final class Searches { + + public static final String SEARCH = "/api/fares?route=LHR-JFK"; + + /** One answer. Status -1 means the request itself failed (see body). */ + public record Reply(int status, String body) { + } + + private static final HttpClient HTTP = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(10)) + .executor(Executors.newVirtualThreadPerTaskExecutor()) + .build(); + + private final ExecutorService senders = Executors.newVirtualThreadPerTaskExecutor(); + private final List> futures = new ArrayList<>(); + private final AtomicInteger failed = new AtomicInteger(); + + private Searches() { + } + + /** Starts {@code count} requests for {@code path} at the same moment and returns straight away. */ + public static Searches start(int port, int count, String path, Duration timeout) { + Searches searches = new Searches(); + CountDownLatch go = new CountDownLatch(1); + for (int i = 0; i < count; i++) { + searches.futures.add(searches.senders.submit(() -> { + go.await(); + Reply reply = send(port, path, timeout); + if (reply.status() != 200) { + searches.failed.incrementAndGet(); + } + return reply; + })); + } + go.countDown(); + return searches; + } + + public static Searches start(int port, int count) { + return start(port, count, SEARCH, Duration.ofSeconds(30)); + } + + /** Requests that have already come back with something other than 200. */ + public int failed() { + return failed.get(); + } + + /** Waits for every answer. */ + public List finish() { + List replies = new ArrayList<>(); + try { + for (Future future : futures) { + replies.add(future.get(60, TimeUnit.SECONDS)); + } + return replies; + } catch (Exception e) { + throw new IllegalStateException("A request did not come back: " + e, e); + } finally { + senders.shutdownNow(); + } + } + + public static Reply send(int port, String path, Duration timeout) { + try { + HttpResponse response = HTTP.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) + .timeout(timeout).GET().build(), HttpResponse.BodyHandlers.ofString()); + return new Reply(response.statusCode(), response.body()); + } catch (Exception e) { + return new Reply(-1, e.getClass().getSimpleName() + ": " + e.getMessage()); + } + } + + /** "20 of 30 searches failed, for example: 503 {...}", or "" when all 200. */ + public static String failures(List replies) { + List failed = replies.stream().filter(reply -> reply.status() != 200).toList(); + if (failed.isEmpty()) { + return ""; + } + String body = failed.getFirst().body(); + return failed.size() + " of " + replies.size() + " searches failed, for example: " + failed.getFirst().status() + " " + + (body.length() > 220 ? body.substring(0, 220) + "..." : body); + } +} diff --git a/java/concepts/junior-mid/18-virtual-threads/start/src/test/resources/logback-test.xml b/java/concepts/junior-mid/18-virtual-threads/start/src/test/resources/logback-test.xml new file mode 100644 index 0000000..1296fbb --- /dev/null +++ b/java/concepts/junior-mid/18-virtual-threads/start/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %d{HH:mm:ss.SSS} %-5level %logger{30} - %msg%n + + + + + + + From e0352a0027ffbebec488e96be92830e5f4089ee0 Mon Sep 17 00:00:00 2001 From: mama-samba-braima Date: Wed, 2 Dec 2026 22:26:28 +0000 Subject: [PATCH 2/2] CI: fall back to Google's mirror of Maven Central when Central refuses the download --- .github/workflows/concepts.yml | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/.github/workflows/concepts.yml b/.github/workflows/concepts.yml index bc054d4..43c7c83 100644 --- a/.github/workflows/concepts.yml +++ b/.github/workflows/concepts.yml @@ -58,10 +58,18 @@ jobs: with: path: ~/.m2/wrapper key: maven-wrapper-${{ runner.os }}-${{ hashFiles('java/concepts/**/.mvn/wrapper/maven-wrapper.properties') }} - - name: Download Maven (with retries) + # Maven Central sometimes refuses a runner outright. After two failed tries, switch this + # job to Google's mirror of Central for both the Maven download and the dependencies. + - name: Download Maven (with retries, then a mirror) run: | cd "${{ matrix.project.path }}/solution" - for i in 1 2 3 4 5; do ./mvnw -q -v && exit 0; echo "attempt $i failed, retrying"; sleep $((i * 10)); done + for i in 1 2; do ./mvnw -q -v && exit 0; echo "attempt $i failed, retrying"; sleep 10; done + mirror=https://maven-central.storage-download.googleapis.com/maven2 + echo "Maven Central refused the download. Using $mirror for this job." + echo "MVNW_REPOURL=$mirror" >> "$GITHUB_ENV" + mkdir -p ~/.m2 + printf 'googlecentral%s\n' "$mirror" > ~/.m2/settings.xml + for i in 1 2 3; do MVNW_REPOURL=$mirror ./mvnw -q -v && exit 0; echo "mirror attempt $i failed, retrying"; sleep 10; done exit 1 # start/ must fail with the documented count; solution/ must pass everything. - name: Verify start/ and solution/ @@ -86,13 +94,25 @@ jobs: with: path: ~/.m2/wrapper key: maven-wrapper-${{ runner.os }}-${{ hashFiles('java/concepts/**/.mvn/wrapper/maven-wrapper.properties') }} - - name: Download Maven (with retries) + - name: Download Maven (with retries, then a mirror) shell: pwsh run: | - for ($i = 1; $i -le 5; $i++) { - & java/concepts/junior-mid/06-thread-safety/solution/mvnw.cmd -q -v + $mvnw = "java/concepts/junior-mid/06-thread-safety/solution/mvnw.cmd" + for ($i = 1; $i -le 2; $i++) { + & $mvnw -q -v if ($LASTEXITCODE -eq 0) { exit 0 } - Write-Host "attempt $i failed, retrying"; Start-Sleep -Seconds ($i * 10) + Write-Host "attempt $i failed, retrying"; Start-Sleep -Seconds 10 + } + $mirror = "https://maven-central.storage-download.googleapis.com/maven2" + Write-Host "Maven Central refused the download. Using $mirror for this job." + "MVNW_REPOURL=$mirror" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 + New-Item -ItemType Directory -Force -Path "$HOME/.m2" | Out-Null + "googlecentral$mirror" | Out-File -FilePath "$HOME/.m2/settings.xml" -Encoding utf8 + $env:MVNW_REPOURL = $mirror + for ($i = 1; $i -le 3; $i++) { + & $mvnw -q -v + if ($LASTEXITCODE -eq 0) { exit 0 } + Write-Host "mirror attempt $i failed, retrying"; Start-Sleep -Seconds 10 } exit 1 # Hosted Windows runners cannot run the Postgres containers, so this checks what it can: