diff --git a/.dockerignore b/.dockerignore index 94810d0..5f628d0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,6 @@ +# Keep the build context small and free of local files * -!target/*-runner -!target/*-runner.jar -!target/lib/* -!target/quarkus-app/* \ No newline at end of file +!pom.xml +!src/ +!mvnw +!.mvn/ diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b93c301 --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Copy to .env (ignored by git) and adjust. Read by docker-compose.yml only. +DB_NAME=quarkus_tutorial +DB_USER=quarkus +DB_PASSWORD=change-me +APP_PORT=8080 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..48239db --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,30 @@ +## Branch + + + +## Task checklist + + + +- [ ] + +## Commit summary + + + +## Test checklist + +- [ ] Unit tests pass +- [ ] Integration tests pass (where the branch's checklist calls for them) +- [ ] `mvn verify` is green on the whole project + +## Code review checklist + +- [ ] No business logic in JAX-RS resources +- [ ] Success responses are wrapped in `ApiResponse`, errors are RFC 9457 Problem Details (`HttpProblem`), never `ApiResponse` on an error path +- [ ] Permission checks are declarative (`@PermissionsAllowed`), no manual permission `if` +- [ ] Every `@CacheResult` has its matching `@CacheInvalidate` on the write operations +- [ ] Every RBAC mutation calls `AuditLogger` +- [ ] The database schema only changes through a Flyway migration +- [ ] No manual Testcontainers setup (Dev Services only) +- [ ] Commits are atomic (one commit per file added or modified), follow Conventional Commits, no em dash, no Claude/Anthropic mention diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1c84069 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,87 @@ +name: CI + +on: + push: + branches: [master, develop] + pull_request: + branches: [master, develop] + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Java 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "21" + cache: maven + + # No "services: postgres" block on purpose. Quarkus Dev Services starts its own PostgreSQL + # container through the Docker daemon already available on ubuntu-latest, exactly as it does + # locally, so the tests need nothing provisioned by the workflow. + - name: Build and test + run: ./mvnw -B verify + + # Slower and independent of the test job: it compiles the application to a GraalVM native + # executable, checks that Dockerfile.native builds, and measures JVM mode against native mode. + native-build: + runs-on: ubuntu-latest + + # The packaged application (not the tests) needs a real database, so this job does declare a + # PostgreSQL service. Dev Services only exists in dev and test mode. + services: + postgres: + image: postgres:16 + env: + POSTGRES_DB: quarkus_tutorial + POSTGRES_USER: quarkus + POSTGRES_PASSWORD: ci-only-password + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U quarkus -d quarkus_tutorial" + --health-interval 5s --health-timeout 3s --health-retries 10 + + env: + DB_URL: jdbc:postgresql://localhost:5432/quarkus_tutorial + DB_USER: quarkus + DB_PASSWORD: ci-only-password + # The repository's development key pair, fine for a throwaway CI database. + JWT_PUBLIC_KEY_LOCATION: ${{ github.workspace }}/dev-keys/publicKey.pem + JWT_PRIVATE_KEY_LOCATION: ${{ github.workspace }}/dev-keys/privateKey.pem + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Java 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "21" + cache: maven + + - name: Package the JVM application + run: ./mvnw -B package -DskipTests + + # container-build compiles inside a Mandrel builder container, so no local GraalVM is needed. + - name: Build the native executable + run: ./mvnw -B package -Dnative -Dquarkus.native.container-build=true -DskipTests + + - name: Measure JVM mode against native mode + run: | + { + echo "| Mode | Ready after (ms) | Reported startup (s) | RSS after load (MB) |" + echo "|---|---|---|---|" + scripts/measure-startup.sh jvm java -jar target/quarkus-app/quarkus-run.jar + scripts/measure-startup.sh native target/*-runner + } | tee -a "$GITHUB_STEP_SUMMARY" + ls -l target/*-runner + + - name: Check that Dockerfile.native builds + run: docker build -f Dockerfile.native -t quarkus-tutorial:native . diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml new file mode 100644 index 0000000..8188482 --- /dev/null +++ b/.github/workflows/pr-checks.yml @@ -0,0 +1,43 @@ +name: PR checks + +on: + pull_request: + branches: [master, develop] + +jobs: + commit-lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Validate commit messages (Conventional Commits) + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + + pattern='^(feat|fix|refactor|test|docs|chore|build|ci|style|perf)\([a-z0-9.,/_-]+\): .{1,100}$' + failed=0 + + while IFS= read -r subject; do + [ -z "$subject" ] && continue + if [[ "$subject" =~ $pattern ]]; then + echo "OK: $subject" + else + echo "INVALID: $subject" + failed=1 + fi + done < <(git log "$BASE_SHA..$HEAD_SHA" --no-merges --pretty=format:'%s') + + if [ "$failed" -ne 0 ]; then + echo "" + echo "One or more commit messages do not follow Conventional Commits." + echo "Expected format: (): " + echo "Allowed types: feat, fix, refactor, test, docs, chore, build, ci, style, perf" + exit 1 + fi diff --git a/.gitignore b/.gitignore index 7349837..784e66e 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ logs/ # JVM crash logs hs_err_pid* replay_pid* + +# Production JWT keys used with docker-compose +keys/ diff --git a/Dockerfile.jvm b/Dockerfile.jvm new file mode 100644 index 0000000..6fa0f73 --- /dev/null +++ b/Dockerfile.jvm @@ -0,0 +1,28 @@ +# Multi-stage image for the packaged JVM application. +# Stage 1 compiles and packages with Maven, stage 2 keeps only a JRE and the Quarkus runnable output. + +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /build + +# Copying the pom alone first lets Docker cache the dependency download until the pom changes. +COPY pom.xml . +RUN mvn -B -q dependency:go-offline + +COPY src ./src +# Tests are skipped here: they rely on Dev Services, which needs a Docker daemon a build stage +# does not have. They run in CI with mvn verify instead. +RUN mvn -B -q package -DskipTests + +FROM eclipse-temurin:21-jre +WORKDIR /app + +# Run as a non-root user so a compromised process has no rights on the container. +RUN useradd --system --no-create-home quarkus +USER quarkus + +# quarkus-app is the fast-jar layout: dependencies sit in separate directories that rarely change, +# so rebuilding after a code change only replaces a small layer. +COPY --from=build --chown=quarkus /build/target/quarkus-app/ ./ + +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "quarkus-run.jar"] diff --git a/Dockerfile.native b/Dockerfile.native new file mode 100644 index 0000000..b6115f6 --- /dev/null +++ b/Dockerfile.native @@ -0,0 +1,30 @@ +# Multi-stage image for the GraalVM native executable. +# Stage 1 compiles the application to a native binary with Mandrel (Red Hat's GraalVM distribution), +# stage 2 keeps only that binary on a minimal runtime image: no JVM, no Maven, no sources. + +FROM quay.io/quarkus/ubi9-quarkus-mandrel-builder-image:jdk-21 AS build +USER root +WORKDIR /build + +# The builder image ships Mandrel but not Maven, so the Maven wrapper is used. Copying the wrapper and +# the pom alone first lets Docker cache the dependency download until the pom changes. +COPY mvnw . +COPY .mvn .mvn +COPY pom.xml . +RUN ./mvnw -B -q dependency:go-offline + +COPY src ./src +# -Dnative switches on the pom's native profile. Tests are skipped here: they rely on Dev Services, +# which needs a Docker daemon a build stage does not have, and they run in CI with mvn verify. +RUN ./mvnw -B -q package -Dnative -DskipTests + +# The runtime image only needs the C libraries the native binary links against. +FROM quay.io/quarkus/ubi9-quarkus-micro-image:2.0 +WORKDIR /work + +# Same idea as Dockerfile.jvm: never run as root. +COPY --from=build --chown=1001:root --chmod=0755 /build/target/*-runner /work/application + +EXPOSE 8080 +USER 1001 +ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/README.md b/README.md index 4ca6fee..b8f6951 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Three everyday Quarkus mechanics this tutorial relies on throughout, worth under | Component | Choice | |---|---| -| Framework | Quarkus 3.30.x (LTS stream) | +| Framework | Quarkus 3.33.x (LTS stream) | | Language | Java 21 (LTS) | | Build | Maven | | REST layer | Quarkus REST (`quarkus-rest`, `quarkus-rest-jackson`) - the current name for what was previously branded "RESTEasy Reactive" | @@ -220,7 +220,7 @@ public record ApiResponse( **Errors**: every non-2xx response is a **Problem Details** document (RFC 9457, which obsoletes RFC 7807 - same `application/problem+json` wire format), produced by the `quarkus-http-problem` Quarkiverse extension rather than a hand-written `ExceptionMapper`. -- `ResourceNotFoundException` and `BusinessRuleException` extend `io.quarkiverse.resteasy.problem.HttpProblem` directly and are thrown normally from a service method - `HttpProblem` already *is* a `RuntimeException`, built via its own builder (`.withTitle(...)`, `.withStatus(...)`, `.withDetail(...)`), so there's no separate DTO and no manual mapping step for these two +- `ResourceNotFoundException` and `BusinessRuleException` extend `io.quarkiverse.httpproblem.HttpProblem` directly and are thrown normally from a service method - `HttpProblem` already *is* a `RuntimeException`, built via its own builder (`.withTitle(...)`, `.withStatus(...)`, `.withDetail(...)`), so there's no separate DTO and no manual mapping step for these two - `quarkus-http-problem` ships its own built-in mappers for the exceptions a project doesn't throw on purpose: Bean Validation failures become a Problem with a `violations` extension listing each field, and anything unmapped becomes a generic 500 Problem with implementation details stripped out before the response is sent - both without a single line of this project's own code - A response's `type`/`title`/`status`/`detail` fields carry what an `ApiResponse` used to carry in `message`, and any structured, field-level detail (like a validation error list) rides in the same document's `extensions` rather than a nested `data` @@ -251,16 +251,16 @@ Example error response (`GET /api/v1/products/999` on a missing product): ### Tasks -- [ ] Generate the project (`mvn io.quarkus:quarkus-maven-plugin:create`, or code.quarkus.io), Java 21, Maven -- [ ] Extensions: `quarkus-rest`, `quarkus-rest-jackson`, `quarkus-hibernate-orm-panache`, `quarkus-jdbc-postgresql`, `quarkus-flyway`, `quarkus-hibernate-validator`, `quarkus-smallrye-jwt`, `quarkus-smallrye-jwt-build`, `quarkus-security`, `quarkus-smallrye-openapi`, `quarkus-smallrye-health`, `quarkus-cache`, `quarkus-scheduler`, `io.quarkiverse.resteasy.problem:quarkus-http-problem` -- [ ] A custom `@Readiness` check (`DatabaseHealthCheck`, verifying a real connection can be obtained) alongside the default one `quarkus-smallrye-health` already provides, and a custom `@Liveness` check confirming the application isn't in a stuck state - both visible at `/q/health`, and individually at `/q/health/ready`/`/q/health/live` -- [ ] Test extensions: `quarkus-junit5`, `rest-assured` -- [ ] `ApiResponse`, `PageResponse` -- [ ] `ResourceNotFoundException`, `BusinessRuleException` (both extending `HttpProblem`, built via its builder with the appropriate status/title); `quarkus-http-problem` configuration (base `type` URI prefix, whether stack traces are ever included - never in `%prod`) -- [ ] Flyway script `V1__init_schema.sql` (all tables from both domains) -- [ ] `application.properties`: JWT signing key location, Flyway enabled, `%test`/`%dev` profiles left without a configured datasource (Dev Services provisions PostgreSQL automatically), `%prod` profile with a real connection string -- [ ] `docker-compose.yml` (app + PostgreSQL, for the packaged application only - not used in dev/test), `Dockerfile.jvm` -- [ ] `.github/workflows/ci.yml`: `mvn verify` (Dev Services provisions PostgreSQL inside the CI runner automatically, same as locally) +- [x] Generate the project (`mvn io.quarkus:quarkus-maven-plugin:create`, or code.quarkus.io), Java 21, Maven +- [x] Extensions: `quarkus-rest`, `quarkus-rest-jackson`, `quarkus-hibernate-orm-panache`, `quarkus-jdbc-postgresql`, `quarkus-flyway`, `quarkus-hibernate-validator`, `quarkus-smallrye-jwt`, `quarkus-smallrye-jwt-build`, `quarkus-security`, `quarkus-smallrye-openapi`, `quarkus-smallrye-health`, `quarkus-cache`, `quarkus-scheduler`, `io.quarkiverse.httpproblem:quarkus-http-problem` +- [x] A custom `@Readiness` check (`DatabaseHealthCheck`, verifying a real connection can be obtained) alongside the default one `quarkus-smallrye-health` already provides, and a custom `@Liveness` check confirming the application isn't in a stuck state - both visible at `/q/health`, and individually at `/q/health/ready`/`/q/health/live` +- [x] Test extensions: `quarkus-junit`, `quarkus-junit-mockito`, `rest-assured` +- [x] `ApiResponse`, `PageResponse` +- [x] `ResourceNotFoundException`, `BusinessRuleException` (both extending `HttpProblem`, built via its builder with the appropriate status/title); the problem `type` URI is a constant on each exception (this version of `quarkus-http-problem` has no type prefix option) and stack traces are never included in a response, in any profile +- [x] Flyway script `V1__init_schema.sql` (all tables from both domains) +- [x] `application.properties`: JWT signing key location, Flyway enabled, `%test`/`%dev` profiles left without a configured datasource (Dev Services provisions PostgreSQL automatically), `%prod` profile with a real connection string +- [x] `docker-compose.yml` (app + PostgreSQL, for the packaged application only - not used in dev/test), `Dockerfile.jvm` +- [x] `.github/workflows/ci.yml`: `mvn verify` (Dev Services provisions PostgreSQL inside the CI runner automatically, same as locally) ## feature/auth @@ -278,15 +278,15 @@ Example error response (`GET /api/v1/products/999` on a missing product): ### Tasks -- [ ] `User` entity, `ActivationToken`, `BlacklistedToken`, `PasswordResetToken` -- [ ] `UserRepository` (`PanacheRepository`) -- [ ] `AuthService` (interface) + implementation: registration, activation, login (password hashing/verification via `io.quarkus.elytron.security.common.BcryptUtil.bcryptHash`/`matches`, from `quarkus-elytron-security-common` - already on the classpath via `quarkus-security`, not an external library), logout, forgot/reset password -- [ ] `forgotPassword` returns the exact same response - same status code, same body, roughly the same timing (no early return skipping the token-generation work) - whether or not the submitted email matches an existing account, so the endpoint can't be used to enumerate registered emails -- [ ] `JwtIssuer`: builds a signed JWT (`io.smallrye.jwt.build.Jwt`) with a unique `jti` claim, the user's id as subject -- [ ] `@SecurityScheme(securitySchemeName = "jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")` declared once (e.g. on `AuthResource` or a dedicated `OpenApiConfig` class) and referenced via `@SecurityRequirement(name = "jwt")` on protected resources, so Swagger UI's "Authorize" button actually works against `@PermissionsAllowed`-protected endpoints -- [ ] A `ContainerRequestFilter` (or `SecurityIdentityAugmentor`, same class introduced fully in `feature/rbac`) checking the incoming JWT's `jti` against `BlacklistedToken` and rejecting the request if found -- [ ] `AuthResource` -- [ ] Tests (`@QuarkusTest` + RestAssured): register → activate → login → access `/me`, logout followed by a rejected request with the same token, forgot/reset password flow +- [x] `User` entity, `ActivationToken`, `BlacklistedToken`, `PasswordResetToken` +- [x] `UserRepository` (`PanacheRepository`) +- [x] `AuthService` (interface) + implementation: registration, activation, login (password hashing/verification via `io.quarkus.elytron.security.common.BcryptUtil.bcryptHash`/`matches`, from `quarkus-elytron-security-common`, a Quarkus module declared explicitly in the pom because `quarkus-security` does not bring it in, not an external library), logout, forgot/reset password +- [x] `forgotPassword` returns the exact same response - same status code, same body, roughly the same timing (no early return skipping the token-generation work) - whether or not the submitted email matches an existing account, so the endpoint can't be used to enumerate registered emails +- [x] `JwtIssuer`: builds a signed JWT (`io.smallrye.jwt.build.Jwt`) with a unique `jti` claim, the user's id as subject +- [x] `@SecurityScheme(securitySchemeName = "jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")` declared once (e.g. on `AuthResource` or a dedicated `OpenApiConfig` class) and referenced via `@SecurityRequirement(name = "jwt")` on protected resources, so Swagger UI's "Authorize" button actually works against `@PermissionsAllowed`-protected endpoints +- [x] A `ContainerRequestFilter` (or `SecurityIdentityAugmentor`, same class introduced fully in `feature/rbac`) checking the incoming JWT's `jti` against `BlacklistedToken` and rejecting the request if found +- [x] `AuthResource` +- [x] Tests (`@QuarkusTest` + RestAssured): register → activate → login → access `/me`, logout followed by a rejected request with the same token, forgot/reset password flow ## feature/rbac @@ -313,18 +313,18 @@ Full CRUD for users, roles, and permissions. Assignments always flow in one dire ### Tasks -- [ ] `Role`, `Permission`, `AuditLog` entities, `RoleRepository`, `PermissionRepository`, `AuditLogRepository` -- [ ] `RbacService` (interface) + implementation: +- [x] `Role`, `Permission`, `AuditLog` entities, `RoleRepository`, `PermissionRepository`, `AuditLogRepository` +- [x] `RbacService` (interface) + implementation: - `createRole`/`updateRole`/`deleteRole` - `deleteRole` rejects if any user is still assigned this role (must be unassigned first) - `createPermission`/`updatePermission`/`deletePermission` - `deletePermission` rejects if any role still has this permission assigned - `assignPermissionToRole`/`removePermissionFromRole` - `removePermissionFromRole` rejects removing `ROLE:WRITE` from a role if doing so would leave **zero** users anywhere holding a role that grants `ROLE:WRITE` - `assignRoleToUser`/`removeRoleFromUser` - `removeRoleFromUser` applies the same last-admin check at the point of removal from a specific user, so a self-lockout is caught however it's attempted -- [ ] `AuditLogger`: a single `log(String action, String entityType, Long entityId, String details)` method, called from every method above - every RBAC mutation is traceable (who did what, to what, when), not just the happy-path ones -- [ ] `PermissionSecurityIdentityAugmentor` (`SecurityIdentityAugmentor`): after JWT validation, loads the user's roles and permissions, adds each `RESOURCE:ACTION` string to the identity as a `StringPermission` -- [ ] `UserResource`, `RoleResource`, `PermissionResource`, each method annotated `@PermissionsAllowed("...")` as listed above - `UserResource` only manages role assignment on existing users, it never creates a user directly (registration stays exclusively `feature/auth`'s job) -- [ ] A seeding step (a `@Observes StartupEvent` method, or a Flyway data-migration): baseline permissions covering every resource/action this project defines, assigned to a seeded `ADMIN` role - without this, nobody could ever be granted `ROLE:WRITE`/`PERMISSION:WRITE` to create the first assignment -- [ ] `ExpiredTokenCleanupJob` (`@Scheduled(cron = "0 0 3 * * ?")`, `quarkus-scheduler`): daily job deleting `BlacklistedToken`/`ActivationToken`/`PasswordResetToken` rows past their expiry, so both tables stay bounded over time - revocation and expiry checks never depend on the row still existing, so deleting it later is purely housekeeping, not a correctness concern -- [ ] Tests: full CRUD on roles and permissions, the "still referenced" rejection on both `deleteRole` and `deletePermission`, the augmentor granting the expected permissions for a multi-role user, a `@PermissionsAllowed`-protected endpoint accepting/rejecting correctly, and specifically the last-admin rejection triggered both ways (removing the role from the last user who has it, and removing the permission from the role that was their only source of it), plus an assertion that every mutation above produces a matching `AuditLog` row +- [x] `AuditLogger`: a single `log(String action, String entityType, Long entityId, String details)` method, called from every method above - every RBAC mutation is traceable (who did what, to what, when), not just the happy-path ones +- [x] `PermissionSecurityIdentityAugmentor` (`SecurityIdentityAugmentor`): after JWT validation, loads the user's roles and permissions, adds each `RESOURCE:ACTION` string to the identity as a `StringPermission` +- [x] `UserResource`, `RoleResource`, `PermissionResource`, each method annotated `@PermissionsAllowed("...")` as listed above - `UserResource` only manages role assignment on existing users, it never creates a user directly (registration stays exclusively `feature/auth`'s job) +- [x] A seeding step (a `@Observes StartupEvent` method, or a Flyway data-migration): baseline permissions covering every resource/action this project defines, assigned to a seeded `ADMIN` role - without this, nobody could ever be granted `ROLE:WRITE`/`PERMISSION:WRITE` to create the first assignment (done as the Flyway migration `V2__seed_baseline_rbac.sql`; an optional `AdminBootstrap` startup observer, active only when `app.bootstrap-admin.email` and `app.bootstrap-admin.password` are set and given dev-only defaults in `%dev`, creates the first administrator, since nobody can otherwise hold `ADMIN`) +- [x] `ExpiredTokenCleanupJob` (`@Scheduled(cron = "0 0 3 * * ?")`, `quarkus-scheduler`): daily job deleting `BlacklistedToken`/`ActivationToken`/`PasswordResetToken` rows past their expiry, so both tables stay bounded over time - revocation and expiry checks never depend on the row still existing, so deleting it later is purely housekeeping, not a correctness concern +- [x] Tests: full CRUD on roles and permissions, the "still referenced" rejection on both `deleteRole` and `deletePermission`, the augmentor granting the expected permissions for a multi-role user, a `@PermissionsAllowed`-protected endpoint accepting/rejecting correctly, and specifically the last-admin rejection triggered both ways (removing the role from the last user who has it, and removing the permission from the role that was their only source of it), plus an assertion that every mutation above produces a matching `AuditLog` row ## feature/categories @@ -340,10 +340,10 @@ Full CRUD for users, roles, and permissions. Assignments always flow in one dire ### Tasks -- [ ] `Category` entity, repository, contract/implementation service -- [ ] Business rule: deleting a category that still has products is rejected (`BusinessRuleException` → 422) -- [ ] `CategoryResource` -- [ ] Tests for every endpoint, including the rejection case and a permission-denied case +- [x] `Category` entity, repository, contract/implementation service +- [x] Business rule: deleting a category that still has products is rejected (`BusinessRuleException` → 422) +- [x] `CategoryResource` +- [x] Tests for every endpoint, including the rejection case and a permission-denied case ## feature/products @@ -361,10 +361,10 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Product` entity, repository, contract/implementation service -- [ ] `ProductService.findById` annotated `@CacheResult(cacheName = "product-cache")`; `ProductServiceImpl.update`/`delete` annotated `@CacheInvalidate(cacheName = "product-cache")` on the same key - a product read hits Panache once and the cache for every subsequent read until it's changed, and every write explicitly clears its own entry rather than leaving a stale cached value silently served -- [ ] `ProductResource` -- [ ] Tests, including the category filter, a permission-denied case, and a cache test asserting a second read doesn't hit the repository while an update correctly invalidates the entry +- [x] `Product` entity, repository, contract/implementation service +- [x] `ProductServiceImpl.findById` annotated `@CacheResult(cacheName = "product-cache")`; `ProductServiceImpl.update`/`delete` annotated `@CacheInvalidate(cacheName = "product-cache")` on the same key (`@CacheKey` on the id) - a product read hits Panache once and the cache for every subsequent read until it's changed, and every write explicitly clears its own entry rather than leaving a stale cached value silently served. The annotations sit on the implementation class, not on the `ProductService` interface: ArC does not apply interceptor bindings declared on an interface method +- [x] `ProductResource` +- [x] Tests, including the category filter, a permission-denied case, and a cache test asserting a second read doesn't hit the repository while an update correctly invalidates the entry ## feature/customers @@ -380,9 +380,9 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Customer` entity, repository, contract/implementation service -- [ ] `CustomerResource` -- [ ] Tests +- [x] `Customer` entity, repository, contract/implementation service +- [x] `CustomerResource` +- [x] Tests ## feature/orders @@ -396,18 +396,18 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice` -- [ ] `OrderResource` -- [ ] Tests, including the total computation +- [x] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice` +- [x] `OrderResource` +- [x] Tests, including the total computation ## feature/native-build (bonus) ### Tasks -- [ ] `Dockerfile.native` (multi-stage: GraalVM builder image, minimal runtime image) -- [ ] Build a native executable locally (`mvn package -Dnative -Dquarkus.native.container-build=true`, container build so a local GraalVM install isn't required) -- [ ] Measure and document, in this branch's own notes: startup time and resident memory of the JVM-mode application versus the native executable, under the same request load -- [ ] `.github/workflows/ci.yml` extended with a native build verification job (can be slower/separate from the main test job) +- [x] `Dockerfile.native` (multi-stage: GraalVM builder image, minimal runtime image) +- [x] Build a native executable locally (`mvn package -Dnative -Dquarkus.native.container-build=true`, container build so a local GraalVM install isn't required). Built and run by the CI job, since the local Docker VM (1.4 GiB) is too small for it, see `docs/native-build.md` +- [x] Measure and document, in this branch's own notes (`docs/native-build.md`): startup time and resident memory of the JVM-mode application versus the native executable, under the same request load +- [x] `.github/workflows/ci.yml` extended with a native build verification job (can be slower/separate from the main test job) ## feature/reactive-endpoints (bonus) @@ -421,11 +421,11 @@ Quarkus lets imperative (blocking, Panache-based) and reactive (Mutiny-based) co ### Tasks -- [ ] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way -- [ ] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched -- [ ] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to -- [ ] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure -- [ ] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread +- [x] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way +- [x] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched +- [x] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to +- [x] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure +- [x] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread ## Order of work diff --git a/dev-keys/privateKey.pem b/dev-keys/privateKey.pem new file mode 100644 index 0000000..be63156 --- /dev/null +++ b/dev-keys/privateKey.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCoqv1HT9KAUuN+ +zVSpNuOnjrlXVc+AdVqtJDK5Vs0FeHzg5Qkz7Wx1QKd53XRXYu9KGb6qCjP3LYJ3 +7uMJ/6CnPLuomhqy3ZmnKV/v/dKXrInwt+ibr1ZLatvKCNFNMamjl+AGjZ3n3f5a +ahYLZP/SZOk7ttaAS5fXT+34efZt27afjNErW0sqe8EBpj6YbzvM1TrBb+E/m2nb +Tz6yYu/qnn6vVkYcqPwArEkkz9KHSFFkwUqIzP4FCavzzmwRcN2sUlM0x1w3PPaL +Vqh5XZmgEwYTKJsE6lp8gf76WZNBwLiN2WEopEU3EoXDwt3waSLh1blL0X8lX+Cr +q1k74scZAgMBAAECggEAFsKIDfTn/1fwCd7UQ0c8XhJk0TOrnfZ4B3AghiD/5nKV +S1Wssbyii4nvb4LiHZ6kkpe5wkFBNOQHvH5YVbOQbrDD0+MDokpD3yo2n3BdWAk4 +zepLMaLt3pxrTy50a9m9Pe2TFd9LRQwQNAwnsF7vJGlojZ3FASfyM+Q9xO9UQQuS +URu9DfjAswcfBcMPbfoVKvHO1bs3srwoosl02h5JdY5B0NAuZTfTUfny5VKoCXvz +aYz0xOIcQaN37tZjA9YUHy2Oxw0xkNBS8yeKArmquJyhbIMf9clQJVeIZD8yEMfe +WGVRG+9dXmZIPzbMGhmFnei+0vqTiF50n8Q5SFxnVwKBgQDXrtCD+PuZOdkfuBFU +BchWiEUaSIc+4TgQ4E2fQD4Jma7QNYxIGwAbPYMtn5vdRdBVem0knCKZ/Z6TZxeA +tgYXrsbkgeTzKxLb0XPdKDOlPcWSTBcWo0alOGslC/V0FikZhoZkWo66H7A/6MbL +2Rc85hpEMDHY9xJV9X6XxpreZwKBgQDIMlgbwyW8kfd1y/XT+l8hN8w25CirOmVG +vrSS/wPAjuv3KWL1/aiSqriIfIvKLWTLbX68UCI+wF+3o1P3LQLSsOoi8G2lXC3u +rsF8Js7fM1p+Aav/eFdUyvsczpqXrkO9w3c+mJqUJPS+nH/gGeg7imQdefP1lhh7 +DxP14VK+fwKBgGiLpSkDTDmGj9dPKp8WungvT4eg9mWlV77eauGxiyCuLM1h12Cw +LcoGdApuXmfQSl7UnAjt4dvQ0sfSZdMO6D8cie4DhI3WKCsDCO1/aiFDovv6BAsG +E91MTqtDc7PUdhGYYpZMSvivGYiw9YOj9B6hzsOUtOTdRjcCa114eGMrAoGAUS9h +XbjQx9zl3oZc5Z7mDyGClkwGVhHzWjIiJm52RhNvi6bj89/vCbNj7C2dvtqTwo9f +0twoVwxKhL0eYuGFAI4wFQUtYd603dNOsZtHT2qS6wCgkJRrzf4WwYLjXFmWLRFk +fSUDosot2lK65NV8wRCJMw7uqQw6V0UxEghTNt8CgYEAq8s+cOm58P40P4j56QA2 +8AdOKVdOfVKZx2R6akB8p8co4naQluhh2pjotPoWSR4BhJSvwi99CETz3hW+7HeW +AbW/1Um9b683C85F8YrUSJD+WZ+02q3Sh4mR2V/7T852zKcAGmfCwBAGVRafD9FL +FFLZHW6Udu/Vux4nJow7rO8= +-----END PRIVATE KEY----- diff --git a/dev-keys/publicKey.pem b/dev-keys/publicKey.pem new file mode 100644 index 0000000..6f4167c --- /dev/null +++ b/dev-keys/publicKey.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKr9R0/SgFLjfs1UqTbj +p465V1XPgHVarSQyuVbNBXh84OUJM+1sdUCned10V2LvShm+qgoz9y2Cd+7jCf+g +pzy7qJoast2Zpylf7/3Sl6yJ8Lfom69WS2rbygjRTTGpo5fgBo2d593+WmoWC2T/ +0mTpO7bWgEuX10/t+Hn2bdu2n4zRK1tLKnvBAaY+mG87zNU6wW/hP5tp208+smLv +6p5+r1ZGHKj8AKxJJM/Sh0hRZMFKiMz+BQmr885sEXDdrFJTNMdcNzz2i1aoeV2Z +oBMGEyibBOpafIH++lmTQcC4jdlhKKRFNxKFw8Ld8Gki4dW5S9F/JV/gq6tZO+LH +GQIDAQAB +-----END PUBLIC KEY----- diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..c649194 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,50 @@ +# Runs the PACKAGED application with a real PostgreSQL. It is not used in dev or test: +# there, Dev Services starts the database by itself. +# +# Before the first "docker compose up --build": +# 1. cp .env.example .env and set the passwords +# 2. create a production RSA key pair in ./keys (the keys under src/main/resources/jwt are +# for development only): +# mkdir -p keys +# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out keys/privateKey.pem +# openssl pkey -in keys/privateKey.pem -pubout -out keys/publicKey.pem +# chmod 644 keys/*.pem +# The container runs as an unprivileged user whose uid differs from yours, so the keys must +# be readable by others. The keys directory is ignored by git and mounted read-only. + +services: + db: + image: postgres:16 + environment: + POSTGRES_DB: ${DB_NAME:-quarkus_tutorial} + POSTGRES_USER: ${DB_USER:-quarkus} + POSTGRES_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD in .env} + volumes: + - db-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-quarkus} -d ${DB_NAME:-quarkus_tutorial}"] + interval: 5s + timeout: 3s + retries: 10 + + app: + build: + context: . + dockerfile: Dockerfile.jvm + depends_on: + db: + condition: service_healthy + environment: + DB_URL: jdbc:postgresql://db:5432/${DB_NAME:-quarkus_tutorial} + DB_REACTIVE_URL: postgresql://db:5432/${DB_NAME:-quarkus_tutorial} + DB_USER: ${DB_USER:-quarkus} + DB_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD in .env} + JWT_PUBLIC_KEY_LOCATION: /keys/publicKey.pem + JWT_PRIVATE_KEY_LOCATION: /keys/privateKey.pem + volumes: + - ./keys:/keys:ro + ports: + - "${APP_PORT:-8080}:8080" + +volumes: + db-data: diff --git a/docs/native-build.md b/docs/native-build.md new file mode 100644 index 0000000..6c9e3f3 --- /dev/null +++ b/docs/native-build.md @@ -0,0 +1,55 @@ +# Native build notes + +Notes for `feature/native-build`: how the native executable is built, and what it changes compared +with the JVM application. + +## How it is built + +- `Dockerfile.native` is a two stage build. Stage one compiles the application with Mandrel (Red Hat's + GraalVM distribution) through the pom's `native` profile. Stage two copies only the resulting binary + onto a micro runtime image, so no JVM, Maven or sources ship. +- Without Docker, the same executable comes from + `./mvnw package -Dnative -Dquarkus.native.container-build=true -DskipTests`. The build runs inside a + Mandrel builder container, so no local GraalVM install is needed. +- The CI job `native-build` in `.github/workflows/ci.yml` does both, builds the executable and checks that + `Dockerfile.native` builds, on every push and pull request. It is separate from the test job because it + takes around ten minutes. + +## Measurements + +Produced by `scripts/measure-startup.sh`, run by the CI job on the same runner, against the same +PostgreSQL 16 service, with the same load for both modes: 300 sequential requests cycling over +`/q/health/ready`, `/q/openapi` and a secured endpoint (401). + +| Mode | Ready after (ms) | Startup reported by Quarkus (s) | RSS after the load (MB) | +|---|---|---|---| +| JVM (`java -jar quarkus-run.jar`) | 4021 | 3.832 | 249 | +| Native executable | 156 | 0.126 | 127 | + +The native executable is about 103 MB on disk. + +Reading the figures: + +- Startup is roughly 25 times faster in native mode. The JVM has to load and link classes and JIT compile + at start, while the native binary already has its heap initialised and its code compiled. +- Memory after the load is about half. It is a single run on a shared CI runner, so treat the ratios as an + order of magnitude and not as a benchmark. The JVM figure would keep changing with more traffic, since + the JIT and the heap grow with it. +- The JVM run is the first to start against the empty database and so applies the Flyway migrations, while + the native run only validates them. That favours native by a few tens of milliseconds at most. +- What is given up: native builds take minutes and several GB of memory, the binary is tied to one + platform, and peak throughput after a long warm up is usually better on the JVM. + +## Issues found while getting it to compile + +- A `static final SecureRandom` in `AuthServiceImpl` failed the native build, because it was created while + the image was built and its seed would have been frozen into the image. It is now a field of the bean, created + when the application starts. This is a good example of the closed world model: code that runs at class + initialisation time is executed at build time in native mode. + +## Building locally + +Compiling a native image needs several GB of memory in the builder container (the CI build peaks at about +3.4 GB). On the development machine used for this tutorial, Docker Desktop was limited to 1.4 GiB, and the +build was killed by the out of memory killer, so the executable was built and measured in CI instead. Raise +the memory of the Docker VM to at least 6 GB to build locally. diff --git a/pom.xml b/pom.xml index 10e13b0..5611ad9 100644 --- a/pom.xml +++ b/pom.xml @@ -11,6 +11,7 @@ 21 UTF-8 UTF-8 + 3.33.2 quarkus-bom io.quarkus.platform 3.33.3.2 @@ -43,6 +44,71 @@ io.quarkus quarkus-arc + + io.quarkus + quarkus-hibernate-orm-panache + + + io.quarkus + quarkus-jdbc-postgresql + + + io.quarkus + quarkus-hibernate-reactive-panache + + + io.quarkus + quarkus-reactive-pg-client + + + io.quarkus + quarkus-flyway + + + io.quarkus + quarkus-flyway-postgresql + + + io.quarkus + quarkus-hibernate-validator + + + io.quarkus + quarkus-smallrye-jwt + + + io.quarkus + quarkus-smallrye-jwt-build + + + io.quarkus + quarkus-security + + + io.quarkus + quarkus-elytron-security-common + + + io.quarkus + quarkus-smallrye-openapi + + + io.quarkus + quarkus-smallrye-health + + + io.quarkus + quarkus-cache + + + io.quarkus + quarkus-scheduler + + + io.quarkiverse.httpproblem + quarkus-http-problem + ${quarkus-http-problem.version} + io.quarkus quarkus-junit @@ -53,6 +119,11 @@ rest-assured test + + io.quarkus + quarkus-junit-mockito + test + diff --git a/scripts/measure-startup.sh b/scripts/measure-startup.sh new file mode 100755 index 0000000..567f671 --- /dev/null +++ b/scripts/measure-startup.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Starts the application, waits until it is ready, sends a fixed request load, then prints one +# markdown table row: time until /q/health/ready answers, the startup time Quarkus itself reports, +# and the resident memory of the process after the load. +# +# Usage: scripts/measure-startup.sh