PixelSense (API) Documentation LLD
PixelSense Backend – Technical Documentation
1. Introduction
PixelSense is a visual testing platform that compares different versions of an application to automatically detect visual regressions — color changes, element displacement, layout shifts, button changes, and other pixel-level differences. Automated UI tests submit screenshots through the PixelSense SDK, and the backend compares them against approved baseline images, flags any visual differences, and surfaces them through a React UI for review.
The backend service (module image-compare-service, base package org.example.pixelsense) is a Spring Boot application responsible for:
- Receiving images and test metadata from the PixelSense SDK
- Running pixel-level and OCR-based comparisons against stored baselines
- Storing comparison results and serving cached/DB-backed data to the React frontend
- Issuing signed URLs so clients can download images directly from Artifactory
- Handling authentication (JWT) and authorization for the platform.
2. Technology stack
| Layer | Technology |
|---|---|
| Language | Java 17 |
| Framework | Spring Boot 3.1.5 |
| Build tool | Maven |
| Packaging | JAR |
| Database | MySQL |
| Data access | Spring JDBC — no JPA/Hibernate; the repository layer uses plain SQL statements and stored procedures |
| Cache | Redis (Spring Data Redis) |
| Auth | JWT (io.jsonwebtoken / jjwt) |
| Image comparison | OpenCV |
| OCR | Tesseract (via Bytedeco) + Leptonica |
| API docs | springdoc-openapi (Swagger UI) |
| Monitoring | Spring Boot Actuator |
| Logging | SLF4J with Logback (logback-spring.xml) |
3. Core dependencies (from pom.xml)
Web & API
spring-boot-starter-web— REST controllers and embedded serverspringdoc-openapi-starter-webmvc-ui(2.6.0) — Open API/Swagger documentationspring-boot-starter-validation— request payload validation
Data access
spring-boot-starter-jdbc— JDBC-based data access (no JPA); repository methods use SQL/stored procedures directlymysql-connector-j(runtime) — MySQL driver
Caching
spring-boot-starter-data-redis— Redis client integrationspring-boot-starter-cache— Spring caching abstraction
Security / Auth
spring-boot-starter-security— core security frameworkjjwt-api,jjwt-impl,jjwt-jackson(0.11.5) — JWT generation, parsing, and validationjackson-datatype-jsr310— JSON (de)serialization support forjava.timetypes used in tokens/DTOs
Image comparison & OCR
org.openpnp:opencv(4.9.0-0) — core pixel-level image comparison engineorg.bytedeco:tesseract-platform(5.3.4-1.5.10) — OCR text extraction from imagesorg.bytedeco:leptonica-platform(1.84.1-1.5.10) — image processing library backing Tesseract OCR
Other
spring-boot-starter-webflux— used for its reactiveWebClient(outbound HTTP calls), not as a reactive serverspring-boot-starter-mail— outbound email notificationsspring-boot-starter-actuator— health checks and monitoring endpointslombok(optional) — boilerplate reduction (getters/setters/builders)spring-boot-starter-test(test scope) — unit/integration testing
4. Project structure
Base package: org.example.pixelsense
org.example.pixelsense
├── cache Redis cache access/config
├── config Spring configuration classes
├── controller REST API endpoints
├── dto Request/response data objects
├── exception Custom exceptions & global error handling
├── mail Email sending logic
│ ├── layout
│ └── templates
├── repository SQL/stored-procedure based data access (no JPA)
├── security
│ ├── auth
│ ├── jwt JWT generation, validation, filters
│ ├── pixelbridge SDK-facing auth/bridge logic
│ └── user
├── service Business logic layer
└── util Shared utilities
src/main/resources
tessdata/— Tesseract OCR trained data filesapplication.properties— app configurationlogback-spring.xml— logging configuration (SLF4J/Logback)
Controllers
AccessTokenController, AdminController, BaselineAnalyticsController, BaselineController, CheckpointController, CompareController, ComparisonController, FeatureController, ImageController, InvitationController, LegacyOcrController, OcrController, OrganizationController, PixelBridgeController, ProfileController, ProjectController, RegionController, TestRunController, UserController, VariantController, VariantImageController, VisualComparisonController
5. Layered architecture
The backend follows a standard three-layer architecture:
Controller → Service → Repository → Database
- Controller layer — exposes REST endpoints, handles request/response mapping and validation
- Service layer — contains business logic, orchestrates calls to one or more repositories, caches, and external systems (Artifactory, Redis)
- Repository layer — executes SQL queries and stored procedures directly against MySQL via Spring JDBC. There is no ORM (JPA/Hibernate) in use.
6. Authentication (overview)
Authentication is JWT-based, implemented in org.example.pixelsense.security.jwt:
JwtService— generates access tokens, refresh tokens, and password-reset tokens (HS256, signed with a configured secret); also validates and parses claims (email, role) from incoming tokensJwtAuthenticationFilter— intercepts requests to validate the token and set the security contextJwtAuthenticationEntryPoint— handles unauthorized access responsesJwtConstants— shared constants for the JWT layer
Token expirations (access, refresh, reset) are externally configurable via application.properties.
A detailed authentication flow (login, token refresh, Pixel Bridge/SDK auth) will be documented separately.
7. Logging
Logging is handled via SLF4J, configured through logback-spring.xml. Logging is applied across the service layer to capture cache lookups, DB queries, comparison results, and errors.
8. Request lifecycle
ImageCompareApplication.main() calls SpringApplication.run(), which bootstraps the Spring application context: it scans and creates all beans (controllers, services, repositories, security filters, JwtService, etc.), auto-configures the embedded Tomcat server, and registers Spring MVC's DispatcherServlet against it. From that point the application is listening for HTTP requests.
DispatcherServlet** is the Front Controller** for the whole application — there is a single instance handling every request, and it is responsible for routing each one to the correct @Controller method. Concretely, a request travels through these stages before it reaches business logic:
- Embedded Tomcat accepts the TCP connection and parses the raw HTTP request.
- Servlet filter chain runs first — this is where Spring Security's filters live, including PixelSense's
JwtAuthenticationFilter. For a protected endpoint, the filter validates the JWT (from theaccessTokencookie) and populates the security context before the request is allowed any further. If validation fails,JwtAuthenticationEntryPointshort-circuits the chain and returns 401 without ever reaching a controller. DispatcherServletreceives the request from the filter chain. Using Spring'sHandlerMapping, it matches the request's URL + HTTP method against@RequestMapping/@PostMapping/@GetMappingannotations to find the target controller method — e.g.POST /api/user/login→UserController.login(...).HandlerAdapterinvokes that method, first resolving its parameters:@RequestBodyis deserialized from JSON into a DTO (e.g.LoginRequest) via Jackson,@CookieValuepulls values straight from request cookies,@RequestParamfrom the query string, and so on.- Controller — deliberately thin. It unwraps the resolved request, delegates to the Service layer, catches exceptions, and wraps the result in the project's standard
ApiResponse<T>envelope before returning aResponseEntity. - Service — holds the business logic: validation, orchestration across repositories/cache/other services, and decisions about what error to throw.
- Repository — executes the actual SQL/stored procedure against MySQL via Spring JDBC and returns plain Java objects (no JPA entities/proxies involved).
- The return value flows back up through Service → Controller →
DispatcherServlet, where aHttpMessageConverter(Jackson) serializes theApiResponseto JSON and writes it to the response — which then passes back out through the filter chain to the client.
9. Worked example: login and token refresh (UserController → UserService)
This section traces a real endpoint through every layer, using the actual UserController/UserService code as the reference.
9.1 POST /api/user/login
- Controller (
UserController.login): accepts aLoginRequestbody and the rawHttpServletResponse(needed to set cookies directly). It callsservice.Login(email, password). - Service (
UserService.Login):- Validates the email/password aren't blank and are within length limits.
- Loads the user via
repository.GetUserByEmail(email). - Verifies the password against the stored hash, supporting three formats side by side for backward compatibility: BCrypt (
$2...prefix), a legacy PBKDF2 format (contains:), and plain text as a last-resort fallback for very old records. - Auto-migrates the password to BCrypt on successful login if it wasn't already BCrypt-hashed (
repository.UpdatePassword) — so old accounts get upgraded transparently the next time they log in. - Strips the password hash off the returned
Userobject before handing it back to the controller.
- Back in the controller, on success:
-
service.updateLastLoginTime(...)andservice.acceptPendingInvitesOnLogin(...)run as side effects (the latter is best-effort and never fails the login).JwtServicegenerates an access token and a refresh token.AuthTokenService.storeRefreshToken(...)writes the refresh token into Redis, keyed by email, with the refresh token's expiry as its TTL.setAuthCookies(...)(viaCookieUtil) writes both tokens as cookies on the response — this is httpOnly cookie-based auth, not a token returned in the JSON body.- Response body is
ApiResponse<LoginResponse>containing the user id, email, role, and organization.
- On any exception, the controller returns 401 with either the exception's message or a generic "Invalid email or password" — deliberately not distinguishing wrong password from account-not-found in the response.
9.2 POST /api/user/refresh
Reads the refreshToken cookie (not a request body) and rotates it:
- If the cookie is missing → 401.
- Validate the JWT signature/expiry via
JwtService.validate. - Extract the email from the token's claims.
- Look up the currently valid refresh token for that email in Redis (
AuthTokenService.getRefreshToken). - Compare the Redis-stored token against the one the browser sent — this is what makes the flow rotation-based: only the most recently issued refresh token is accepted. If they don't match (e.g. an older/stolen token is reused), the request is rejected as invalid.
- On a match: load the user, issue a new access token and a new refresh token, delete the old Redis entry, store the new refresh token, and set both cookies again.
The endpoint logs every one of these steps individually via SLF4J (logger.info/logger.warn) — but never logs the raw token. Instead it computes a short SHA-256 fingerprint (tokenFingerprint(...), first 12 hex chars) purely so log lines can be correlated without ever exposing a usable token value in log files.
9.3 Other UserController endpoints (summary)
| Endpoint | Purpose |
|---|---|
POST /api/user/forgot-password | Sends a password-reset OTP if the account exists; response is identical either way (prevents email enumeration) |
POST /api/user/reset-password | Verifies the OTP and sets a new password; distinct HTTP status per failure type (expired/invalid/rate-limited OTP) |
POST /api/user/logout | Invalidates the Redis refresh token and clears both cookies |
POST /api/user/send-otp | Sends a signup OTP; rejects if the email is already registered |
POST /api/user/register | Verifies OTP, hashes the password, creates the user, sends a notification email, and optionally accepts a pending project invite by token |
POST /api/user/delete-account | Re-authenticates with email/password (not a session) before deleting — used from the signup/invite flow when an email already has an account |
GET /api/user/active | Lists active users for a project |
GET/POST /api/user/profile-image | Fetches/uploads a user's profile image |
GET /api/user/assignments, GET/assignments/unread-count, POST /assignments/mark-seen | Project assignment notifications for a user |
GET /api/user/me | Resolves the current user from the accessToken cookie |
10. Domain glossary
| Term | Definition |
|---|---|
| Organization | The top-level tenant. Contains Projects and the people (Users) who belong to it. |
| Project | One application under test, scoped to an Organization. Has a name, description, status (e.g. active/completed), and an owner (createdBy). |
| Feature | A named grouping within a Project — e.g. "Checkout flow" — that Baselines are organized under. |
| Baseline | The approved "golden" reference image for a Feature/screen. Carries its own resolution, browser, and storage path, plus a set of accepted regions. |
| Variant | A version of a Baseline. A single Baseline can have multiple Variants (e.g. for different browsers/resolutions); a Variant can define its own accepted regions in addition to the Baseline's. |
| Checkpoint (a.k.a. TestRun) | One screenshot captured during an automated test scenario — effectively one step in a larger scenario. Carries its own resolution, browser, OS, and storage path. This is the "current" image that gets compared against a Baseline/Variant. |
| Comparison | The result record produced when a Checkpoint is compared against a Baseline/Variant: whether it matched (isMatched), the generated diff image (diffStoragePath), and the coordinates of flagged differences (diffRegionsJson). |
| Region | An area within an image, usually rectangular, of one of two kinds: an Ignore Region (excluded from comparison — differences inside it are never flagged) or a Selected Region (the opposite — comparison is restricted to only that area). |
| PixelBridge | The SDK that sits between the automation suite and the backend API. Requests authenticated with an X-PixelBridge-Token are locked server-side to whichever single Project the token was issued for — the client cannot override this by passing a different projectId, which prevents a token for one Project from being used to write into another. |
| Invitation | (pending confirmation) — ties to a Project; accepted automatically on login for any pending invite matching the user's email (see acceptPendingInvitesOnLogin). |
Comparison vs. VisualComparison controllers — these are two different sides of the same data, not duplicates:
VisualComparisonController(POST /api/visual/compare) is the write path: the SDK/automation submits a screenshot here to be run through the comparison engine.ComparisonController(GET /api/comparison/{checkId}) is the read path: the frontend calls this to fetch aComparisonDetailsrecord (baseline/checkpoint/variant image URLs, match status, diff regions) for display.
11. AccessTokenController — /api/projects/{projectId}/tokens
Manages PixelBridge access tokens — the credentials automation projects use to authenticate against VisualComparisonController via the X-PixelBridge-Token header.
| Endpoint | Method | Purpose |
|---|---|---|
/api/projects/{projectId}/tokens | POST | Generate a new token for the project |
/api/projects/{projectId}/tokens | GET | List tokens issued for the project |
/api/projects/{projectId}/tokens/{tokenId} | DELETE | Revoke a token |
Auth: all three require a normal JWT login (CustomUserDetails must be present — 401 if not). Beyond that, every operation calls requireOwnedProject(...), which restricts access to **the project's creator, or a user whose account-level role is **ADMIN — anyone else gets a 403 (ProjectAccessDeniedException).
Token generation (POST)
Request body: CreateAccessTokenRequest (token name, optional).
The generated token is pxbr_ + a Base64url AES-256-GCM ciphertext of tokenId.userId.projectId. That's a deliberate design choice worth noting in the doc:
- The token is self-describing once decrypted — resolving it directly yields which user + project issued it, with no hash-lookup table scan needed.
- The GCM authentication tag makes it tamper-proof: flipping any bit fails decryption outright rather than silently resolving to a different user/project.
- The row is inserted in two phases: first with a random throwaway secret (so the DB row gets an id), then patched with the real prefix/hash once the real token — which embeds that same row's id — has been built.
- Only a SHA-256 hash and a short display prefix are persisted. The raw token is returned exactly once in the response and never stored in plaintext.
- The response also includes an
apiUrlSecret: the API's public URL, AES-256-GCM encrypted with a key derived from the raw token itself (SHA-256(rawToken)). This means the automation side only needs to hold the access token + this secret together — there's no separately-deployed URL-secret key to manage.
Response: ApiResponse<AccessTokenIssuedResponse> → { token (AccessToken row), rawToken, apiUrlSecret }, 201 Created.
List tokens (GET)
Returns ApiResponse<List<AccessToken>> for the project — ownership-checked the same way.
Revoke (DELETE)
Loads the token by id and defense-in-depth checks it actually belongs to both the given projectId and the requesting user (via .equals(), since these are UUID objects) before revoking — on top of the project-ownership check already performed. Sets revokedAt; a revoked token then fails resolution permanently (see below).
Supporting service logic (not exposed as its own endpoint, but used elsewhere)
resolve(rawToken)— this is what actually authenticates incomingX-PixelBridge-Tokenheaders (called from the security filter chain, not this controller). Decrypts the token; any decryption failure (forged/tampered/wrong key) returnsnullrather than throwing. On successful decryption, does one primary-key lookup to confirm the token hasn't been revoked and that the embedded user/project IDs still match the stored row.touchLastUsed(tokenId)— updateslast_used_atfor bookkeeping only; failures here are swallowed so a logging hiccup can never break authentication.
Error handling
| Exception | Status |
|---|---|
userDetails == null | 401 |
ProjectAccessDeniedException | 403 |
IllegalArgumentException (generate) | 422 |
IllegalArgumentException (list/revoke) | 404 |
| Anything else | 500 |
11.2 ComparisonController — /api/comparison
The read path: fetches a comparison result for the frontend to display.
| Endpoint | GET /api/comparison/{checkId} |
| Auth | Not specified in this controller (no explicit permitAll/role annotation visible here — inherits whatever the default security chain requires) |
| Path variable | checkId (UUID) — the Checkpoint being looked up |
| Response | ComparisonDetails — baseline/checkpoint/variant image URLs, isMatched, diff region JSON, and metadata (resolution, browser, OS, created dates) for all three images involved |
ComparisonService.GetComparisonDetails resolves this in three tiers, so the same endpoint returns something useful at every stage of a checkpoint's lifecycle:
Case 1 — a Comparison already exists. The most common case, once a checkpoint has actually been run through the comparison engine. Returns the full ComparisonDetails record: baseline, checkpoint, matched, and result image paths are each converted into signed, temporary Artifactory URLs, and the same is done for every Variant's image. Accepted-region fields (baseline-level and per-variant) that are blank are normalized to null rather than returned as empty strings, so the frontend can treat "no regions defined" consistently.
Case 2 — no Comparison yet, but the Checkpoint exists. This covers a checkpoint that's been created and uploaded but hasn't been compared against anything yet (or was never matched against a baseline). A fallback ComparisonDetails is built directly from the checkpoint's own metadata: checkpointImageUrl is generated from the checkpoint's storage path, along with its created date, browser, resolution, and OS — but baselineImageUrl, matchedImageUrl, resultImageUrl, and comparisonId are all left null, and variants is returned as an empty list.
Case 3 — nothing found at all. Neither a Comparison nor a Checkpoint exists for the given checkId. Returns an essentially empty ComparisonDetails (no image URLs, no regions, empty variants list) rather than a 404 — the endpoint always returns a 200 with a ComparisonDetails shape, and the frontend distinguishes "nothing to show" by the absence of image URLs rather than by HTTP status.
11.4 AdminController — /api/admin
Administrative operations: app-wide settings (baseline limits, diff highlight color) and user management (create, list, reset password). No project scoping — this is instance-level, not per-project.
| Endpoint | Method | Purpose |
|---|---|---|
/api/admin/settings | POST | Save an admin's settings (baseline limit + highlight color) |
/api/admin/settings | GET | Fetch an admin's settings (adminId query param) |
/api/admin/users | POST | Create a new user (admin-provisioned, not self-signup) |
/api/admin/users | GET | List all users (for the User Management table) |
/api/admin/users/reset-password | POST | Admin-initiated password reset for another user |
Auth: not enforced at the controller level in this class (no @AuthenticationPrincipal check, unlike AccessTokenController) — whatever restricts these endpoints to actual admins must live in SecurityConfig's URL-pattern rules rather than in the method bodies. Worth confirming /api/admin/** is locked to the ADMIN role there, since nothing here does that check directly.
Settings (save / get)
AdminSettingsRequest→{ adminId, baselineLimit, highlightColor }. Validated server-side:baselineLimitmust be 1–50,highlightColormust be a strict 6-digit hex code (#FFFFFFformat).GETfalls back to sane defaults (baselineLimit = 10,highlightColor = "#FF0000") the first time an admin opens Settings, before anything's been saved — no row exists yet, so this isn't an error case.- These settings aren't just cosmetic:
AdminService.getHighlightColor(...)andgetBaselineLimit(...)are called elsewhere (noted: byCompareController) so freshly generated diff images use whichever highlight color was last saved.
Create user (admin-provisioned)
Distinct from the public /api/user/register signup flow (Section 9) — this one skips OTP verification entirely, since an admin is vouching for the account directly.
CreateUserRequest→{ fullName, email, username, phone (optional), role, password }rolemust be one ofADMIN,VIEWER,USER(case-insensitive, normalized to uppercase)- Checks for an existing account by email → 409 Conflict if found
- Password is hashed (BCrypt via
PasswordUtil) before storage - Sends a new-user notification email — failure here is swallowed (
ex.printStackTrace()) and never blocks user creation
List users / reset password
GET /usersreturnsList<AdminUserDto>— no filtering, pagination, or auth check visible in this method.- Reset password takes a raw
newPassworddirectly (min 6 characters) and overwrites the user's hash — no current-password confirmation, since this is an admin-initiated reset, not the user's own self-service flow.
Error handling
| Exception | Status |
|---|---|
IllegalStateException (create user — email exists) | 409 |
IllegalArgumentException | 422 (create user) / 400 (settings, reset password) |
| Anything else | 500 |
11.5 BaselineAnalyticsController — /api/baseline-analytics
Read-only analytics endpoint: baseline/variant counts and creation trends for a project, charted over a date range.
| Endpoint | Method | Purpose |
|---|---|---|
/api/baseline-analytics | GET | Baseline/variant totals + daily trend chart for a project and date range |
Auth: none enforced in the controller itself — relies on whatever global rule covers /api/**, same caveat as AdminController.
Query parameters
| Param | Default | Notes |
|---|---|---|
projectId | required | |
mode | monthly | weekly | monthly | custom |
weekOffset | 0 | Only used in weekly mode — weeks relative to the current one |
monthOffset | 0 | Only used in monthly mode — months relative to the current one |
from, to | none | Only used in custom mode (ISO date) |
Date range resolution by mode
weekly— Monday–Sunday of the weekweekOffsetweeks from the current week (TemporalAdjusters.previousOrSame(MONDAY)+ offset).monthly(also the fallback for any unrecognized mode) — first-to-last day of the monthmonthOffsetmonths from the current month.custom— usesfrom/todirectly; if either is missing, defaults to the last 30 days.
Caching
Results are cached in Redis with a 120-second TTL, keyed on every input that affects the result: analytics:{projectId}:{mode}:{weekOffset}:{monthOffset}:{customFrom}:{customTo}. Because the full parameter set is baked into the key, different filter combinations for the same project simply produce different cache entries rather than colliding — but it also means there's no single "analytics for project X" key to invalidate; stale data just ages out after 120s.
Data computed
- Overall totals — total baseline count and total variant count for the project (all-time, not scoped to the date range), computed via
EXISTSsubqueries joiningimage_baselines→image_entities→test_featuresontest_features.pid. - Trend data — one entry per calendar day in the range (pre-filled with zero so there are no gaps), with baseline-created and variant-created counts per day, built via two separate grouped queries (
queryPerDay).
Response: BaselineAnalyticsResponse → { rangeLabel, totals: { totalBaselines, totalVariants }, chartData: [{ date, baselineCount, variantCount }, ...] }
11.6 BaselineController — /api/baseline
CRUD-ish operations on Baselines: list, fetch a signed image URL, fetch a gallery of images for a test, and delete.
| Endpoint | Method | Purpose |
|---|---|---|
/api/baseline | GET | List all baselines for a project |
/api/baseline/{baselineImgId}/image | GET | Signed URL for one baseline's image |
/api/baseline/images/{testId} | GET | Base64-encoded gallery of baseline images for a test |
/api/baseline/delete | POST | Bulk-delete baselines by ID |
Auth: none enforced in the controller — same caveat as the last two.
List baselines (GET /api/baseline)
projectId required (400 if missing). Returns List<BaselineImageDetails> — one entry per baseline including featureName, baselineCount, variantCount, and lastUpdatedDate, i.e. this is the summary view used to populate a baseline list/table, not full image bytes.
Signed image URL (GET /{baselineImgId}/image)
This is the image retrieval flow documented earlier in Section 8, concretely: looks up the baseline's stored path, then calls SignedUrlService.generateUrl(...) to produce a temporary Artifactory URL. 404 if the baseline has no image path recorded. Returns the URL as a plain string body (not wrapped in ApiResponse).
Image gallery by test (GET /images/{testId})
This one has real logic worth documenting carefully:
- Despite the path parameter being named
testId, it's used directly asnid— the code comment explicitly confirms these are the same underlying column, just referred to by different names in different parts of the app (BaselineImageDetails.testIdcomes from this same column via a different stored procedure). Worth resolving this naming inconsistency eventually — same ID, two names, is exactly the kind of thing that causes confusion for a new engineer. - The backing stored procedure (
getBaselineCheckpointsWithLatestJsonByNid) returns both baselines and variants together in one result set (UNION ALL). The service filters this: rows withvariantId == nullare true baselines; rows with avariantIdare Variants and are explicitly skipped here, otherwise every Variant would get double-counted as an extra Baseline image. - For each remaining baseline row, downloads the actual image bytes from Artifactory (
ArtifactoryService.downloadImage) and Base64-encodes them directly into the response — unlike the signed-URL endpoint above, this one returns raw image data inline rather than a link.
11.7 CheckpointController — /api/checkpoints
Manages Checkpoints — the screenshots submitted during automated test runs — including creation, image retrieval, promoting a checkpoint to a Baseline, attaching metadata, assigning checkpoints to reviewers, and updating review status.
| Endpoint | Method | Purpose |
|---|---|---|
/api/checkpoints | POST | Create a new checkpoint (uploads the screenshot) |
/api/checkpoints/{checkId}/image | GET | Get a signed URL for the checkpoint's image |
/api/checkpoints/{checkId}/accept-baseline | POST | Promote a checkpoint to a Baseline |
/api/checkpoints/{checkId}/json | POST | Attach JSON metadata to a checkpoint |
/api/checkpoints/{checkId}/assign | POST | Assign a checkpoint to a reviewer |
/api/checkpoints/{checkId}/review | PATCH | Update a checkpoint's review status |
Create checkpoint (POST, multipart/form-data)
Takes nid (the test/feature identifier the checkpoint belongs to), userId, productName, featureName, imageName, and the image file itself.
The flow:
- The image is uploaded to Artifactory first (
ArtifactoryService.uploadImage), organized by product name, feature name, and image name. - The returned storage path, along with
nidand the creating user, is passed toCheckpointService.InsertCheckpoint, which writes the checkpoint row and returns its generatedcheckId.
Response: the new checkpoint's checkId (UUID).
Get checkpoint image (GET /{checkId}/image)
Looks up the checkpoint by id, then generates a signed, temporary Artifactory URL for its stored image — the same signed-URL pattern used for Baseline images. If the checkpoint has no stored image path, this is treated as an error condition.
Accept as baseline (POST /{checkId}/accept-baseline)
This is how a Checkpoint becomes a Baseline — the action a reviewer takes when they decide a screenshot should become the new approved reference image for its Feature.
Inputs: checkId, the accepting userId, and an optional JSON body describing the accepted regions for this new baseline (the regions a reviewer has chosen to treat as "expected" going forward).
Before accepting, the system enforces a per-project baseline limit: it looks up the checkpoint's associated test/feature (nid), reads the current admin-configured baseline limit (from Admin Settings — see Section 11.4), counts how many baselines already exist for that test, and blocks the promotion if the limit has been reached. This keeps a single Feature from accumulating unlimited baseline images over time; a reviewer would need to delete an existing baseline or the limit would need to be raised in Settings before another can be accepted.
If accepted successfully, the checkpoint's storage path and accepted regions are persisted as a new baseline record, and the new baseline's image id is returned.
Insert JSON metadata (POST /{checkId}/json)
Attaches a JSON metadata payload to an existing checkpoint (e.g. captured test context — browser, OS, resolution, or other automation-supplied data). The JSON is validated for well-formedness and size before being stored, and an identifier for the stored JSON record is returned.
Assign checkpoint (POST /{checkId}/assign)
Assigns a checkpoint to a specific user for review — recording who assigned it (assignedBy), who it's assigned to (assignedTo), and an optional remarks note. This is the mechanism behind the assignment-notification endpoints already documented under UserController (/assignments, /assignments/unread-count, /assignments/mark-seen in Section 9.3) — those endpoints read back what gets created here.
Update review status (PATCH /{checkId}/review)
Updates a checkpoint's review outcome. Valid status values are approved, rejected, or pending (case-insensitive) — any other value is rejected. Records which user (userId) performed the review action.
Error handling
| Condition | Response |
|---|---|
| Baseline limit reached (accept-baseline) | 409 Conflict, with a message stating the limit and how to resolve it |
| Invalid input (accept-baseline) | 400 Bad Request |
| Image upload failure (create checkpoint) | Propagated as a runtime error |
11.8 CompareController — /compare
This is the actual image-comparison engine endpoint — separate from VisualComparisonController (Section 11.1), which is the main SDK-facing submission API. CompareController exposes the underlying OpenCV comparison logic directly, secured by a distinct API key scheme rather than JWT/PixelBridge auth.
| Endpoint | Method | Purpose |
|---|---|---|
/compare/v2 | POST | Compare a set of base (baseline) images against one comparison image |
Auth: X-API-KEY header, enforced via the apiKeyScheme security requirement (Swagger-documented) at the controller level — applies to every endpoint in this controller.
Request (multipart/form-data)
| Field | Description |
|---|---|
baseFiles | One or more candidate base/baseline images to compare against |
compareFile | The image being tested |
region (optional) | JSON describing Ignore/Selected regions to apply during comparison |
hexColor (optional) | Hex color for highlighting detected differences on the output image |
adminId (optional) | Used to resolve the highlight color from Admin Settings if hexColor isn't supplied |
If hexColor isn't provided, the admin's currently saved highlight color (Section 11.4) is used instead, so diff boxes on the output image always match whatever theme color is configured in Settings.
How the comparison works (CompareService.compare)
- The comparison image is decoded into an OpenCV
Mat. - If a
regionJSON was supplied, a region mask is built from it (RegionMaskService) — this is what implements the Ignore Region / Selected Region behavior described in the domain glossary: differences falling outside the mask (or inside an ignore area, depending on region type) are excluded from scoring. - Each base image is compared in parallel — one task per base image, run on a thread pool sized to the number of available CPU cores. This lets a checkpoint be compared against multiple candidate baselines simultaneously rather than one at a time.
- For each base image, a pixel-level diff is computed (
QuadTreeService.diff), then the region mask is applied to the diff, and a numeric diff score is produced as the count of differing (non-zero) pixels remaining after masking. - Once all parallel comparisons complete, the base image with the lowest diff score is chosen as the best match.
- Contours (bounding boxes) are drawn around the differing areas of the best match, using the resolved highlight color.
- The result is considered a match if no difference regions (contours) were found at all; otherwise it's a difference, and the output image (with highlighted diff boxes drawn on it) is returned along with the list of difference regions.
Response
- Match: returns the name of the matching base image, a "matched" indicator, and the (empty) region list.
- Difference: returns the diff image (as bytes, boxes drawn on it), the name of the closest-matching base image, and the list of difference regions found.
- Both cases are built via
ResponseHandler, a shared helper for shaping these comparison responses consistently.
Error handling
| Condition | Response |
|---|---|
| Missing/empty base or compare files | Handled via ResponseHandler.invalidImage() |
| Any other failure during comparison | Handled via ResponseHandler.error(...), with the underlying exception message included |
11.9 FeatureController — /api/features
Manages Features — the named groupings within a Project (Section 10) — including listing, deleting, updating, and two summary/reporting views.
| Endpoint | Method | Purpose |
|---|---|---|
/api/features | GET | List all features for a project |
/api/features/delete | POST | Batch-delete features |
/api/features/update | POST | Rename a feature / update its product name |
/api/features/summary | GET | Image run summary for a feature |
/api/features/images | GET | List images belonging to a feature |
Get all features (GET)
Requires a logged-in user (CustomUserDetails from the JWT cookie — 401 if absent). Takes projectId, resolves the current user by email, and returns List<FeatureEntity> scoped to both the project and the user.
Delete features (POST /delete, batch)
Requires login, and additionally requires the ADMIN role — any other role gets 403. Accepts a list of feature IDs (max 1000 per request). After deleting, the FEATURES_ALL Redis cache key is explicitly cleared so the next listing reflects the deletion rather than serving stale cached data.
Update feature (POST /update)
Takes a FeatureEntity body (featureId, featureName, productName) and updates the record. Feature name and product name are each validated as required and capped at 255 characters. Also clears the FEATURES_ALL cache key on success, for the same reason as delete.
Image run summary (GET /summary)
Takes a featureId and returns List<ImageRunSummaryDto> — a summary view of the test runs/checkpoints recorded under that feature.
Get images by feature (GET /images)
Takes a featureId and returns List<ImageByFeatureDto> — the images associated with that feature.
11.10 ImageController — /api/images
This is the endpoint the earlier-documented signed URLs actually point to — the concrete implementation behind the image retrieval flow described in Section 8. Whenever SignedUrlService.generateUrl(...) is called elsewhere (baselines, checkpoints, comparisons), the URL it produces resolves to this endpoint.
| Endpoint | Method | Purpose |
|---|---|---|
/api/images/view | GET | Serve an image from Artifactory, gated by a signed-URL check |
Request
Query parameters: path (the Artifactory storage path), exp (expiry timestamp, epoch seconds), sig (HMAC signature).
How the signature is verified (ImageSecurityService.validate)
- Expiry check — if the current time is past
exp, the request is rejected immediately as expired. - Signature check — the expected signature is computed as
HMAC-SHA256(path + ":" + exp), using the same secret configured for JWT signing (jwt.secret), Base64url-encoded without padding. If this doesn't match thesigsupplied in the request, the request is rejected as invalid.
This means a signed URL is self-contained and stateless: nothing is looked up in the database or Redis to validate it — anyone holding a valid path + exp + sig triple can retrieve that image until exp passes, and there's no server-side revocation mechanism for an individual signed URL once issued.
Serving the image
Once validated, the image bytes are fetched from Artifactory (ArtifactoryService.downloadImage) and returned directly with Content-Type: image/png.
Supporting: how images get into Artifactory in the first place (ArtifactoryService)
- Upload (
uploadImage) — the image is stored under a deterministic path:pixelsense/{productName}/{featureName}/{imageName}/{sha256}.png, where the filename itself is the SHA-256 hash of the image bytes, not the original filename. Uploaded via HTTPPUTto Artifactory with HTTP Basic auth (configured username/password), one path segment at a time URL-encoded. - Download (
downloadImage) — HTTPGETfrom the same computed path, same Basic auth. - Both operations are plain
HttpURLConnectioncalls to Artifactory's REST API — there's no Artifactory SDK/client library in use, it's hand-rolled HTTP.
Error handling
Any failure (expired/invalid signature, Artifactory error, missing image) is caught and returned as a 400 Bad Request with the exception message as the body.
11.11 InvitationController — /api/invitations
Deliberately public/unauthenticated — resolves a project invite link for someone who doesn't have an account yet, so it can't sit behind login the way most endpoints do. Same trust model as a password-reset link: security comes from the token being unguessable, not from an auth check.
| Endpoint | Method | Purpose |
|---|---|---|
/api/invitations/{token} | GET | Resolve an invite token into its project/inviter/status details |
Purpose
Called by the signup page (…/register?invite=TOKEN) to pre-load what the invite screen needs before the person has an account: which project they're being invited to, who invited them, and whether their email already has an account (so the frontend can offer "sign in instead" rather than forcing a new signup).
Behavior
- Empty/blank token → 400.
- Token not found in
user_invitations→ 404, "This invite link is invalid." - Token found but past
expires_at→ 410 Gone, with a message directing the person to ask the project owner to resend it. Note the invitation details are still returned alongside the 410 (notnull), so the frontend can still show which project the (expired) invite was for. - Valid, unexpired token → 200 with the full
InvitationDetails.
InvitationDetails fields (from the underlying query)
token, projectId, projectName, email (the invitee), inviterName, status, isExpired, accountExists (whether the invitee's email already has a User account), createdAt, expiresAt.
Notably, accountExists** is computed live** in the repository method (a GetUserByEmail lookup per row) rather than stored — so it always reflects whether an account exists right now, not at the time the invite was created.
Data model
Backed by a user_invitations table, joined to projects (for the project name) and user (for the inviter's name via invited_by). Confirms the Invitation → Project relationship from the domain glossary: an invitation is scoped to one project, not an Organization.
Error handling
| Condition | Response |
|---|---|
| Blank/missing token | 400 |
| Token not found | 404 |
| Token expired | 410 (Gone) |
| Unexpected error | 500, logged via SLF4J |
11.12 OcrController — /api/pixelbridge/ocr
Extracts text from a screenshot using Tesseract OCR — either from the full image or from specific regions within it. This is where the tesseract-platform/leptonica-platform dependencies from Section 3 actually get used.
| Endpoint | Method | Purpose |
|---|---|---|
/api/pixelbridge/ocr | POST | Run OCR on an uploaded image, optionally restricted to specific regions |
Request (multipart/form-data)
image— the screenshot to OCRregion(optional JSON) — a list ofOcrRegionobjects (x,y,width,height) to crop and OCR individually. If omitted, OCR runs against the full image.
Tesseract initialization (@PostConstruct)
At application startup, the bundled eng.traineddata file (packaged at src/main/resources/tessdata/eng.traineddata) is copied out to a temporary filesystem directory, since Tesseract requires a real filesystem path rather than a classpath resource. The copy is verified by checking the resulting file size is non-zero — catching a truncated/failed copy at startup rather than as a confusing runtime OCR failure later. Startup fails outright if the trained-data file can't be found or copies out empty.
OCR pipeline, per image or per region
- Preprocessing (OpenCV): convert to grayscale, upscale if the crop is shorter than 48px (using cubic interpolation, capped at 6× to avoid over-scaling already-large crops), apply a slight Gaussian blur to soften upscale artifacts, then binarize with Otsu thresholding for clean text/background separation. This pipeline is specifically tuned for small UI text — PixelSense regions are frequently only 6–25px tall in their native screenshot resolution, well below what Tesseract needs for reliable character recognition.
- OCR with automatic retry: the first pass uses Page Segmentation Mode 7 (single text line — appropriate for the common case of a short UI label like a button or price). If confidence comes back below 90%, a second pass is automatically run with PSM 6 (uniform block — better suited to multi-line panels or paragraphs), and whichever pass scored higher is kept. A confidence of 0 or below means Tesseract found no usable text at all, in which case no retry is attempted.
- Result: for each processed region, the extracted text plus Tesseract's mean confidence score (0–100) is returned. Confidence below 90% is logged as a warning suggesting the region may need to be resized or that the source text has low contrast/anti-aliasing issues.
Region-based OCR: reading order
When multiple regions are supplied, results aren't returned in whatever order they were requested — they're re-sorted into natural reading order (top-to-bottom by row, then left-to-right within each row), and each result is stamped with its row index. Rows are grouped by vertical center position using a tolerance derived from the average region height, so regions that are roughly at the same height on screen are treated as being in the same row even if their exact Y-coordinates differ slightly.
Response
OcrServiceResponse → { success, message, results: [{ regionName, x, y, width, height, text, row, confidence }, ...] }. For full-image OCR (no regions supplied), a single result named "FullImage" covering the whole image is returned.
Error handling
| Condition | Response |
|---|---|
| Missing/empty image, invalid region coordinates (negative, zero-size, or exceeding image bounds) | 400, with the validation message |
| Any other OCR/processing failure | 500, with the underlying error message |
11.13 OrganizationController — /api/organization
Org-wide user management for the organization owner — the "Manage Users" panel. Deliberately a separate top-level path from ProjectController rather than nested under /api/projects/{id}/..., because these operations aren't scoped to one project — they act across every project the calling admin owns.
| Endpoint | Method | Purpose |
|---|---|---|
/api/organization/members | GET | List every member of the caller's organization, with access status |
/api/organization/members/{userId}/status | PATCH | Activate/deactivate a member across all the admin's projects |
/api/organization/members/{userId}/role | PATCH | Promote/demote a member between ADMIN and USER |
/api/organization/members/{userId}/projects | GET | Per-project breakdown of one member's access |
/api/organization/members/{userId}/projects/{projectId}/status | PATCH | Activate/deactivate a member on one specific project only |
Auth: requires login (CustomUserDetails, 401 if absent) on every endpoint. There's no separate "are you the org owner" check needed beyond that, because every query is built from the caller's own userId — there's no way to pass in someone else's admin id, so a non-owner calling any of these only ever sees or affects their own (typically empty) organization.
List members (GET /members)
Returns List<OrganizationMemberStatus> — every user who has ever accepted an invite to one of the caller's projects, each with their current overall active/inactive status.
Deactivate/activate — org-wide (PATCH /members/{userId}/status)
Flips the member's access across every one of the admin's projects at once. Deactivating a member immediately hides all of that admin's projects from the member's own "My Projects" list; reactivating restores them. This does not delete the member, their account, or their invite history — it only flips an active/inactive flag. It does not touch that same person's membership in any other admin's organization they might also belong to. An admin cannot deactivate themselves.
Change role (PATCH /members/{userId}/role)
Promotes or demotes a member between ADMIN and USER (case-insensitive input, normalized to uppercase). Only valid for someone who has actually accepted an invite from the calling admin. An admin cannot change their own role through this endpoint.
Per-project access breakdown (GET /members/{userId}/projects)
Returns List<OrganizationMemberProjectStatus> — lets the admin see which of their individual projects a member is currently active or inactive on, rather than only the all-projects aggregate from the main /members listing.
Deactivate/activate — single project (PATCH /members/{userId}/projects/{projectId}/status)
The per-project counterpart to the org-wide status toggle above: touches only the one project named in the path, leaving the member's access to the admin's other projects untouched. This is how an admin keeps a teammate inactive on one specific project while they remain active elsewhere in the organization.
Error handling
| Condition | Response |
|---|---|
| Not logged in | 401 |
IllegalArgumentException (e.g. target user not in caller's org, trying to change own access/role) | 422 |
ProjectAccessDeniedException (single-project status change, not the project owner) | 403 |
| Unexpected error | 500, logged via SLF4J with both the target user id and the acting admin id |
11.14 ProfileController — /api/profile
User profile management: fetching a user's basic profile info, profile image upload/retrieval, and self-service password change.
| Endpoint | Method | Purpose |
|---|---|---|
/api/profile/user/{id} | GET | Fetch a user's profile info by id |
/api/profile/image/{id} | GET | Fetch a user's profile image |
/api/profile/image | POST | Upload/replace the current user's profile image |
/api/profile/change-password | POST | Change the current user's own password |
Auth: GET /user/{id} and GET /image/{id} take no @AuthenticationPrincipal — any authenticated-or-not caller who knows a user's UUID can fetch their profile info and image. POST /image and POST /change-password require a logged-in user (CustomUserDetails), since they act on the caller's own account (userId is taken from the authenticated principal, not a request parameter).
Get user by id (GET /user/{id})
Returns UserDto for the given id, or 404 if not found.
Get profile image (GET /image/{id})
Looks up the stored image path for the user, downloads the bytes from Artifactory, and returns them directly as image/jpeg. Returns 404 if the user has no profile image path set, or if the image can't be retrieved.
Upload profile image (POST /image)
Accepts a profileImage multipart file. The image is uploaded to Artifactory under a fixed path pattern — users/profile/user_{userId} — and the resulting storage path is saved against the current user's profile record.
Change password (POST /change-password)
Takes ChangePasswordDto (currentPassword, newPassword). Verifies the supplied current password against the stored hash using Spring Security's PasswordEncoder.matches(...), then hashes and stores the new password using PasswordEncoder.encode(...).
This is worth noting for anyone reading both sections of this doc together: the password check here goes through Spring Security's own PasswordEncoder, which is a different code path from the manual BCrypt/legacy-PBKDF2/plaintext check in UserService.Login (Section 9.1). PasswordEncoder.matches only understands the encoder it's configured with (typically BCrypt) — so an account whose password is still stored in the legacy PBKDF2 or plaintext format would fail here even though it can still log in normally via /api/user/login, until that account's hash gets auto-migrated to BCrypt (which happens automatically on a successful login, per Section 9.1).
Also worth noting: profile image retrieval and upload exist in two places in the API — here (/api/profile/image*) and also under UserController (/api/user/profile-image, Section 9.3). Both ultimately read/write a profile image path via Artifactory; readers working with profile images should be aware both endpoints exist.
Error handling
| Condition | Response |
|---|---|
User not found (GET /user/{id}) | 404 |
No profile image found (GET /image/{id}) | 404 |
Incorrect current password (change-password) | 400, with message |
| Any other failure | 500, generic message |
11.15 ProjectController — /api/projects
The core project-management controller: create/rename/delete projects, manage team membership (invite, add-existing, list), and view assigned work. Shares ProjectService with OrganizationController (Section 11.13) — this is where most of that service's logic is actually exercised.
| Endpoint | Method | Purpose |
|---|---|---|
/api/projects | GET | List the caller's projects |
/api/projects | POST | Create a new project |
/api/projects/limit | GET | Check the caller's project-count limit/usage |
/api/projects/{id}/name | PATCH | Rename a project |
/api/projects/{id}/status | PATCH | Change a project's lifecycle status |
/api/projects/{id} | DELETE | Soft-delete a project |
/api/projects/{projectId}/members | GET | List a project's team members |
/api/projects/{projectId}/members | POST | Invite a new team member by email |
/api/projects/{projectId}/organization-members | GET | List org members not yet on this project |
/api/projects/{projectId}/members/add-existing | POST | Add an existing org member to this project directly |
/api/projects/{projectId}/assignments | GET | List assigned work for a project |
Auth: every endpoint requires login (CustomUserDetails). Ownership (project.createdBy == userId) is enforced in the service layer for owner-only actions, independently of the controller — the code comment on inviteMember notes this is deliberate: being authenticated isn't the same as owning this specific project.
List / create projects
GET /api/projects— if the caller is an orgADMIN, returns every project under their organization name; otherwise returns only the projects the caller personally created or was added to. Backs the frontend's project switcher and initial routing decision (straight to dashboard vs. "create your first project").POST /api/projects— creates a project. Name must be 3–100 characters, contain at least one letter, and not match a placeholder pattern (bare "test", "demo", "sample", "untitled", etc. — but a real name that merely contains one of those words, like "Demography Dashboard," is allowed). Must be unique among the caller's own projects. Organization is locked per-user: once a user has any project with an organization set, every later project automatically reuses that same organization name — the client-supplied organization value is only used (and validated) the very first time.statusdefaults toACTIVEif omitted; onlyACTIVE/ON_HOLDare valid at creation time (ARCHIVED/COMPLETEDare lifecycle transitions, not creation-time choices).GET /api/projects/limit— returns the caller's organization name, how many active projects it currently has, and the configured maximum (default 2, viaapp.project.max-projects), for the frontend to show usage/limit UI.
Rename / status / delete (owner-only)
- Rename — new name goes through the same validation as creation, and must remain unique among the owner's projects.
- Status update — unlike creation, all four lifecycle values (
ACTIVE,ON_HOLD,ARCHIVED,COMPLETED) are valid targets here. An unrecognized value is rejected outright (422) rather than silently defaulting to something, so a bad request is visible to the frontend rather than looking like a no-op. - Delete — a soft delete: the project row is kept, marked
is_deleted/deleted_by/deleted_at, and simply stops appearing inGET /api/projects. Nothing is physically removed.
Team membership
GET /members— owner-only; lists everyone currently on the project.POST /members(invite by email) — owner-only. Enforces a per-project member cap (default 2, viaapp.project.max-members) before inserting. Duplicate-invite handling is layered and specific:- Already a member of this project → 409, specific message.
- Already accepted an invite to one of this admin's other projects (i.e. already in the admin's organization) → 409 with a distinct payload (
OrganizationMemberConflict, carrying their email/name) so the frontend can offer "add to this project?" instead of a plain error. - Otherwise → a new
Invitationrow is created and an email is sent with a link containing the invite's own opaque token (not the project id or any user id directly — the signup page resolves everything server-side viaGET /api/invitations/{token}, Section 11.11). If the email send itself fails, the invite record is still kept (not rolled back) and the failure is only logged — a bounced email doesn't destroy a valid pending invite.
GET /organization-members— lists people who've already accepted an invite to one of the admin's other projects but aren't yet on this one — backs the "Add existing member" picker as an alternative to a fresh email invite.POST /members/add-existing— grants a known org member immediate access to this project with no new signup email. Requires the requester be either the project owner or an orgADMIN. Only works for someone who has already accepted an invite from this same admin before — this is explicitly not a general "add any user" mechanism.
Assigned work
GET /assignments — the project owner (or an org ADMIN) sees every assignment on the project; anyone else with project access sees only assignments made to themselves. Calling this at all requires the caller to actually be a member of the project (or the owner/admin) — plain authentication isn't sufficient.
Error handling
| Exception | Status |
|---|---|
ProjectLimitExceededException / MemberLimitExceededException | 403 |
ProjectAccessDeniedException | 403 |
AlreadyInOrganizationException | 409, with OrganizationMemberConflict payload |
IllegalStateException (duplicate name, already a member) | 409 |
NoSuchElementException (project not found) | 404 |
IllegalArgumentException (validation failures) | 422 (or 404 for members/organization-members lookups) |
| Anything else | 500, logged via SLF4J with project id and user id |
11.16 RegionController — /api/regions
Persists the Region data described in the domain glossary — the Ignore/Selected areas the frontend lets a reviewer draw on an image. Once saved, these regions are what the comparison engine (RegionMaskService, Section 11.8) reads when a Checkpoint is next compared against that Baseline/Variant.
| Endpoint | Method | Purpose |
|---|---|---|
/api/regions/save | POST | Save (or clear) the regions for a baseline, variant, or checkpoint |
/api/regions/delete | DELETE | Delete one specific region by id |
Save regions (POST /save)
Request: entityType (query param), entityId (query param, UUID), regionsJson (request body).
entityType must be one of exactly three values — baseline, variant, or checkpoint (case-insensitive, normalized to lowercase) — since a region always belongs to one of these three kinds of images. Any other value is rejected.
regionsJson is validated before being persisted:
- Null or blank is explicitly allowed — this is treated as clearing all regions for the entity, not an error.
- Capped at 100,000 characters.
- Must parse as a JSON array.
- Each element in the array must have
x,y,width, andheight;widthandheightmust both be positive.
Once validated, the regions are saved against the given entity. Returns a plain boolean indicating success.
Delete region (DELETE /delete)
Request: entityType, entityId, regionId (the specific region's numeric id), plus an Authorization header.
Restricted to the ADMIN role: the caller's JWT is read directly from the Authorization header (Bearer <token>) and its role claim is extracted and checked before the delete is allowed — any other role gets 403.
How this connects to the comparison engine
Once regions are saved for a Baseline (or Variant), they're read back during comparison and passed into RegionMaskService, which builds the mask that determines which parts of the image are excluded from diffing (Ignore Regions) versus the only parts that are diffed (Selected Regions) — this is the mechanism described in Section 11.8's comparison walkthrough.
Error handling
| Condition | Response |
|---|---|
Invalid entityType, entityId, or malformed regionsJson (save) | IllegalArgumentException — not caught in this controller, so it currently surfaces as a raw 500 rather than a 4xx, the same gap noted for BaselineController and FeatureController |
Invalid regionId, or non-ADMIN role (delete) | 403 for the role check; IllegalArgumentException from validation is likewise uncaught here |
11.18 VariantController — /api/variant
Manages Variants — the per-browser/OS/resolution alternates of a Baseline described in the domain glossary. This confirms the Variant → Baseline relationship concretely: a Variant is created from a Checkpoint being attached to an existing Baseline, not from scratch.
| Endpoint | Method | Purpose |
|---|---|---|
/api/variant/insert | POST | Create a new variant from a checkpoint, under an existing baseline |
/api/variant/delete | GET | Delete a variant |
/api/variant/update | POST | Rename a variant |
Insert variant (POST /insert)
Takes baselineImgId (the Baseline this variant belongs to), checkpointId (the checkpoint whose image becomes the variant's image), variantName, and createdBy. All four are required; variantName is capped at 255 characters. This is the backend counterpart to "accept as baseline" (Section 11.7) — where accepting a checkpoint creates a new Baseline, inserting a variant instead attaches the checkpoint's image to an existing Baseline as an alternate version.
Delete variant (GET /delete)
Deletes by variantId. Returns { "success": true/false } depending on whether a row was actually removed.
Note: this is a
GETrequest that performs a delete (state-changing operation on aGETroute), which differs from thePOST /deletepattern used elsewhere in this API (e.g.BaselineController,FeatureController). Worth being aware of when integrating — aGEThere has side effects, unlike a normal read-onlyGET.
Update variant name (POST /update)
Takes variantId and newName; same name validation as insert (required, ≤255 characters).