diff --git a/CHANGELOG b/CHANGELOG index d586cdb..500ed68 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,26 +1,45 @@ # CHANGELOG +## 11-12-26 +- The client now owns the dashboard state (active and known servers, link state, run state, the server's backup interval and retention, both versions) and pushes it to every open page on `GET /api/client/events`: one `snapshot` on subscribe, then `link`, `state`, `run-started`, `run-finished`, `servers`, `config`, `backups-changed`, `versions` and `ping`. `GET /api/client/dashboard` returns the same snapshot +- Link states: `LIVE` (the server's event stream is open), `DEGRADED` (no stream, because of an older server, the subscriber cap or a backoff, but the server answers its health check), `CONNECTING` (a server was just selected or its stream dropped and the first health check has not answered) and `DOWN` (no server, or the health check failed). While not `LIVE`, the client checks the server's health every 8 seconds, once per client instead of once per open page +- Pages no longer poll the server. Status, Backup Archives and Versions are driven by pushes, and the one-minute refresh only re-reads the client's stored state +- The Backup Archives table reloads when a run finishes, when the server announces `backups-changed` (archive deleted or backup location changed), when the connected server changes, and when the link comes back; on tab return or view return only if a server is connected and its link is up. While `DEGRADED` the client lists the server's archives once a minute and pushes `backups-changed` itself +- The client refetches the server's health on its `config-changed` event, so schedule and retention changes made elsewhere show up at once +- Versions: the client pushes its own update check result when it changes. The server's version is fetched when the link comes up (not again within 5 minutes of a good answer, unless the server was down) or the server changes, then at most hourly; it is asked again after 30 seconds if the server has not checked yet, 5 minutes after a server error and 10 minutes when unavailable. The Versions panel needs no recheck timer, and the server row reads "Unable to check" once the first check fails +- The page shows "Client unreachable" instead of "No server connected" when the client itself cannot be reached. Renewing the live connection does not trigger it: the page waits 8 seconds for the reconnect first. The Server Status panel says when live updates are unavailable from the server +- The Known Servers list updates on every open Dashboard the moment the client's list changes, including background discovery, and leaves a selection you are making alone. The Pickup Interval field is filled on the first successful load and never changed by pushes or refreshes +- When the connected server changes, including in the background, the Dashboard reloads at once, including the Server Config form +- Moved the Versions panel below the Backup Archives panel +- The event stream sends a `retry: 5000` hint and answers 503 with an empty body when 32 browsers are already subscribed +- `GET /api/client/status` no longer probes for the preferred server; background discovery does that, retrying every 4 seconds while no server is selected +- Removed the unused `GET /api/client/server-health` and `GET /api/client/versions` +- "Run Backup Now" now gives up waiting after `CLIENT_BACKUP_RUN_TIMEOUT` (default `PT6H`) instead of holding a request open forever; the client answers 504 saying the backup is probably still running on the server, and the dashboard still shows when it finishes +- Added a small `node --test` suite for the page's decision logic; `make test` runs it + +## 11-11-26 +- The client knows its own version (`0.1.0`) and checks GitHub for the latest release of `MediaGarrd/Client` shortly after starting and then once a day. `MEDIAGARRD_UPDATE_REPOSITORY`, `MEDIAGARRD_GITHUB_API_URL` and `MEDIAGARRD_UPDATE_CHECK_INTERVAL` change the repository, API address and interval; the interval must be at least `PT1H` or the client refuses to start +- Added a Versions panel to the Dashboard with a Server row and a Client row: "Up-to-date" when current, a red box with a link to the latest release when an update is available, muted when the check could not be made or no server is connected. The server's version comes from its `GET /api/v1/version` +- The Dashboard refreshes every minute while open and visible (Backup Archives, Known Servers without disturbing a selection, Versions from the stored status without contacting GitHub); the Pickup Interval field is never touched +- The client keeps one connection to the server's `GET /api/v1/events` and relays it on the new `GET /api/client/events` (`state`, `run-started`, `run-finished`, `ping`, and `link` for the stream's status). The Server Status "State" and the backup buttons switch to Running and back to Idle at once, and Backup Archives reloads when a run finishes +- The client resubscribes when the connected server changes, reconnects after a failure with a delay growing from 1 to 30 seconds, and reconnects when the stream is quiet for 45 seconds. A server without `/api/v1/events` is retried every 5 minutes and polled meanwhile +- The browser closes the live connection while the tab is hidden and reopens it on return; at most 32 browsers can subscribe +- A health check started before a live event no longer overwrites it with older information, and a slow Backup Archives reload no longer overwrites a newer one +- Scheduled tasks run on two threads, so a slow GitHub check cannot delay discovery or pickups + ## 10-26-26 -- Finished renaming the codebase to MediaGarrd -- Added issue templates, issue label and pull request workflows, and integration test workflows -- Added a `Makefile` with a `test` target -- Removed `install.sh`: `docker-compose.example.yml` now works as-is, the container keeps its downloads and state on the mounted volumes by default, and everything else is set from the web page -- `MEDIAGARRD_SERVER_PORT` now defaults to `38471` to match the server, and `MEDIAGARRD_SERVER_IP` is optional and accepts `:` -- The client connects to `MEDIAGARRD_SERVER_IP` on its own at startup and keeps trying every 30 seconds until a server is selected, so scheduled pickups work without opening the web page -- Added a Server Config view, opened from the toggle in the top bar, that changes the connected server's backup location, interval, and retention count and adds, edits, and removes its services -- Split the web page into an HTML page, a stylesheet, and JavaScript modules -- Every API endpoint now returns errors as `{"error": "..."}`, passing on the server's own message and status code when the server rejects a request -- Fixed the server schedule being sent as a number of seconds instead of an ISO-8601 duration -- The Gradle wrapper is now committed so the project builds without a local Gradle install -- Network discovery finishes in a couple of seconds instead of minutes: it checks for an open port before making an HTTP request, probes many hosts at once, skips Docker and VPN interfaces, and only counts servers that answer with a MediaGarrd health response -- Connecting by IP accepts `host:port`, stops right away when the host is unreachable, and scans every port of a reachable host in about a second -- Fixed the connection badge being overwritten by the periodic health check while a scan or connection attempt is running -- The badge and status panel show when the selected server is not responding, the backup list says why it could not be loaded, and everything reloads on its own when the server comes back -- The backup list reloads when a backup run started elsewhere finishes, and the Dashboard shows saved server settings as soon as you switch back to it -- "Scan Local Network" reports how many servers the scan actually found -- Requests to the server now time out instead of hanging when it is unreachable, and health checks pause while the page is hidden -- Starting a download of a backup that is already downloading reuses the running download instead of writing the same file twice -- Unknown backups and download tasks return 404, invalid pickup intervals and server URLs return 400, and finished download tasks are forgotten after 10 minutes -- Backup file names from the server can no longer write outside the download directory -- The client state file is written atomically so a crash cannot leave it half written -- Removed unused code and dependencies +- Finished renaming the codebase to MediaGarrd; removed unused code and dependencies +- Added issue templates, issue label and pull request workflows, integration test workflows, and a `Makefile` with a `test` target. The Gradle wrapper is now committed +- Removed `install.sh`: `docker-compose.example.yml` works as-is, downloads and state stay on the mounted volumes by default, and everything else is set from the web page +- `MEDIAGARRD_SERVER_PORT` defaults to `38471` to match the server; `MEDIAGARRD_SERVER_IP` is optional and accepts `:`. The client connects to it at startup and retries every 30 seconds until a server is selected, so scheduled pickups work without opening the page +- Added a Server Config view, opened from the toggle in the top bar, to change the connected server's backup location, interval and retention count and to add, edit and remove its services +- Split the web page into an HTML page, a stylesheet and JavaScript modules +- Every API endpoint returns errors as `{"error": "..."}`, passing on the server's own message and status code when it rejects a request. Unknown backups and download tasks return 404, invalid pickup intervals and server URLs return 400, and finished download tasks are forgotten after 10 minutes +- Fixed the server schedule being sent as seconds instead of an ISO-8601 duration +- Network discovery finishes in a couple of seconds: it checks for an open port before any HTTP request, probes many hosts at once, skips Docker and VPN interfaces, and counts only servers that answer with a MediaGarrd health response. "Scan Local Network" reports how many it found +- Connecting by IP accepts `host:port`, stops at once when the host is unreachable, and scans every port of a reachable host in about a second +- The badge and status panel show when the selected server is not responding, the backup list says why it could not load, and everything reloads when the server returns. The connection badge is no longer overwritten by the health check during a scan or connection attempt +- The backup list reloads when a run started elsewhere finishes, and the Dashboard shows saved server settings as soon as you switch back to it +- Requests to the server time out instead of hanging, and health checks pause while the page is hidden +- Starting a download of a backup that is already downloading reuses the running download +- Backup file names from the server can no longer write outside the download directory, and the client state file is written atomically diff --git a/Makefile b/Makefile index 9fee8ce..891e440 100644 --- a/Makefile +++ b/Makefile @@ -2,4 +2,5 @@ test: ./gradlew test --warning-mode all + node --test src/test/js/*.test.mjs diff --git a/README.md b/README.md index ce4c774..f2141dd 100644 --- a/README.md +++ b/README.md @@ -23,12 +23,17 @@ The defaults in `docker-compose.yml` work as-is. To change them before the first - **Server port to look for:** `MEDIAGARRD_SERVER_PORT` (default `38471`, the server's default). Discovery and "Connect by IP" try this port first. - **Connect to a server automatically:** add `MEDIAGARRD_SERVER_IP=` (or `:`) to `environment`. Until a server is selected, the client connects to this address as soon as it answers. Without it, pick a server in the web page. +`CLIENT_BACKUP_RUN_TIMEOUT` (ISO-8601, default `PT6H`, minimum `PT1M`; the client refuses to start below that) is how long "Run Backup Now" waits for the server to finish a backup. If it takes longer, the client answers 504 and the page shows an error; the backup keeps running on the server and the dashboard still shows when it finishes. + `CLIENT_PICKUP_INTERVAL` (ISO-8601, default `PT12H`) only sets the initial value. Once the interval has been saved in the web page, the stored value is used. ## Usage - **Dashboard** connects to a MediaGarrd server by IP, from the list of known servers, or by scanning the local network. It shows the server's status, runs a backup, downloads backups, and sets how often the client downloads the latest backup on its own. - **Server Config** changes the connected server's backup location, backup interval, and number of backups to keep, and adds, edits, and removes the services it backs up. The server must have finished its first-time setup (the `/config` page on the server) before it accepts changes from the client. +- **Live status and refresh**: the client keeps the dashboard state (active and known servers, link state, run state, the server's backup interval and retention, and both versions) and pushes every change to each open page through a live connection (see Live events). The Server Status "State" and the backup buttons change to Running the moment a run starts and back to Idle the moment it ends; the Backup Archives table reloads when a run finishes, when the server announces an archive change, when the connected server changes, and when the link comes back. The page does not poll the server. It re-reads the client's stored state once a minute and when a hidden tab becomes visible or the Dashboard is shown again, as a catch-all; the Backup Archives table is also reloaded then, but only when a server is connected and its link is up. A normal end of the live connection (it is renewed every few minutes) does not show "Client unreachable"; that appears only if the client stays unreachable for 8 seconds. The Pickup Interval field is only filled when the page loads and is never changed by pushes or refreshes. +- **Versions** panel on the Dashboard shows the client's and the connected server's version. Each checks GitHub for the latest release once a day. A row says "Up-to-date" when it is current, turns into a red box with a link to the latest release when an update is available, and is muted when the check could not be made (offline, rate limited) or no server is connected. The server needs to be a version that provides `GET /api/v1/version`. + Every setting is stored in the `./data/client/state` volume and survives restarts and container rebuilds. ### Finding servers @@ -36,6 +41,31 @@ Every setting is stored in the `./data/client/state` volume and survives restart With the default Docker networking the client only sees the container network, so a scan finds servers running on the same host but not on other machines. Use "Connect by IP" or `MEDIAGARRD_SERVER_IP` for those, or add `network_mode: host` to the service (and remove its `ports` mapping) so the scan covers your LAN. +## Update alerts +The Versions panel is driven by the `versions` event (`{"client": {...}, "server": {...} | null}`) and the `versions` field of `GET /api/client/dashboard`. Each status has `currentVersion`, `latestVersion`, `releaseUrl`, `updateAvailable`, `checkState` (`OK`, `NO_RELEASES`, `ERROR`, `NOT_CHECKED`, or `UNAVAILABLE` when the server cannot be asked), `checkedAt`, and `message`. `server` is `null` while no server is selected. + +To change what is checked, set `MEDIAGARRD_UPDATE_REPOSITORY` (default `MediaGarrd/Client`), `MEDIAGARRD_GITHUB_API_URL` (default `https://api.github.com`), or `MEDIAGARRD_UPDATE_CHECK_INTERVAL` (ISO-8601, default `PT24H`, minimum `PT1H`) in `environment`. + +## Live events +`GET /api/client/events` is a Server-Sent Events stream for the web page, and `GET /api/client/dashboard` returns the same state as one JSON snapshot without contacting the server. The client keeps one connection to the connected server's `GET /api/v1/events`, owns the dashboard state, and pushes it. Every new subscriber first gets one `snapshot`, followed by granular events: +- `snapshot` `{"activeServer": "", "knownServers": [...], "link": "LIVE|DEGRADED|CONNECTING|DOWN", "running": bool or null, "health": {"backupInterval": "PT6H", "backupRetentionCount": 5} or null, "versions": {"client": {...}, "server": {...} or null}}`: the whole state. Also sent to everyone when the active server changes. +- `link` `{"server": "", "state": "LIVE|DEGRADED|CONNECTING|DOWN"}`. + - `LIVE`: the server's event stream is open, and run state is pushed. + - `DEGRADED`: no event stream (an older server, the server at its subscriber cap, or a reconnect backoff), but the server answers `GET /api/v1/health`. The client polls it every 8 seconds, once per client no matter how many pages are open, and synthesizes `state` events from it. The poll stops when the link is `LIVE`. + - `CONNECTING`: a server was just selected, or its stream just dropped, and the first health check has not answered yet. Run state is unknown. + - `DOWN`: no active server, or no event stream and the last health check failed. Run state is unknown (`running` is `null`) and the client keeps checking. +- `state` `{"running": bool, "at": ""}`, `run-started` `{"running": true, "startedAt": "..."}` and `run-finished` `{"running": false, "status": "COMPLETED|PARTIAL|FAILED", "startedAt": "...", "finishedAt": "..."}`: forwarded from the server. +- `backups-changed` `{"at": ""}`: forwarded from the server when its archive list changed outside a run (an archive was deleted or the backup location changed). While the link is `DEGRADED` the client lists the server's archives once a minute and sends this itself when the list changed, so open pages never ask the server. +- `config` `{"backupInterval": "PT6H", "backupRetentionCount": 5}`: the server's schedule or retention. The client refetches the server's health when the server announces `config-changed`, on link up, and once a minute while the link is `LIVE`, and pushes this only when the values changed. +- `servers` `{"knownServers": [...], "activeServer": ""}`: the client's list of known servers changed (discovery, a scan, a connect). +- `versions` `{"client": {...}, "server": {...} or null}`: the client's update check result changed, or the server's version was fetched. The server's version is fetched when the link comes up (unless it was fetched successfully in the last 5 minutes and the server was not down in between) or the server changes, and at most hourly after that. A version the server has not checked yet is asked for again after 30 seconds, an error after 5 minutes, and an unavailable one after 10 minutes. +- `ping` `{}` every 20 seconds. + +The first event on each stream carries `retry: 5000`, so a browser that loses the client waits 5 seconds before reconnecting. The client reconnects to the server with a growing delay (1 to 30 seconds), resubscribes when the connected server changes, and drops a stream that has been silent for 45 seconds. A server that answers 404 (older than this feature) is tried again every 5 minutes and is `DEGRADED` meanwhile. At most 32 browsers can subscribe at once (further requests get an empty 503). If a reverse proxy sits in front, the response sends `Cache-Control: no-cache` and `X-Accel-Buffering: no`; do not buffer it. + +## Tests +`make test` runs the Java tests (`./gradlew test`) and the browser tests. The browser tests need Node 20.19 or newer, have no dependencies, and can be run on their own with `node --test src/test/js/*.test.mjs`. They cover the pure modules in `src/main/resources/static/js`: `dashboard-model.js` (event reduction and what triggers a reload), `view-model.js` (link state, known servers and versions rendering decisions) and `reachability.js` (when the client counts as unreachable). + ## Updating ```bash git pull diff --git a/build.gradle.kts b/build.gradle.kts index 1c249cd..3a1bf34 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,8 @@ plugins { id("io.spring.dependency-management") version "1.1.6" } +version = "0.1.0" + repositories { mavenCentral() } @@ -21,6 +23,10 @@ java { } } +springBoot { + buildInfo() +} + tasks.test { useJUnitPlatform() } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java b/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java index 6eea406..29bba9a 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java @@ -12,6 +12,10 @@ public class Configuration { private Duration pickupInterval = Duration.ofHours(12); private int serverPort = 38471; private String preferredServerIp = ""; + private String updateRepository = "MediaGarrd/Client"; + private String githubApiBaseUrl = "https://api.github.com"; + private Duration updateCheckInterval = Duration.ofHours(24); + private Duration backupRunTimeout = Duration.ofHours(6); public String getStateFile() { return stateFile; @@ -52,4 +56,36 @@ public String getPreferredServerIp() { public void setPreferredServerIp(String preferredServerIp) { this.preferredServerIp = preferredServerIp; } + + public String getUpdateRepository() { + return updateRepository; + } + + public void setUpdateRepository(String updateRepository) { + this.updateRepository = updateRepository; + } + + public String getGithubApiBaseUrl() { + return githubApiBaseUrl; + } + + public void setGithubApiBaseUrl(String githubApiBaseUrl) { + this.githubApiBaseUrl = githubApiBaseUrl; + } + + public Duration getUpdateCheckInterval() { + return updateCheckInterval; + } + + public void setUpdateCheckInterval(Duration updateCheckInterval) { + this.updateCheckInterval = updateCheckInterval; + } + + public Duration getBackupRunTimeout() { + return backupRunTimeout; + } + + public void setBackupRunTimeout(Duration backupRunTimeout) { + this.backupRunTimeout = backupRunTimeout; + } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java index e092bcd..4108c86 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java @@ -1,7 +1,5 @@ package wellatleastitried.mediagarrdclient.api; -import java.net.SocketTimeoutException; -import java.net.http.HttpTimeoutException; import java.util.Map; import java.util.Objects; @@ -17,6 +15,9 @@ import org.springframework.web.client.RestClientResponseException; import org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; +import wellatleastitried.mediagarrdclient.service.RequestTimeouts; + @RestControllerAdvice public class ApiExceptionHandler { @@ -38,12 +39,20 @@ public ResponseEntity> serverRejected(RestClientResponseExce return error(e.getStatusCode(), reason); } + @ExceptionHandler(BackupRunTimeoutException.class) + public ResponseEntity> backupRunTimedOut(BackupRunTimeoutException e) { + LOGGER.warn("Backup run timed out: {}", e.getMessage()); + return error(HttpStatus.GATEWAY_TIMEOUT, e.getMessage()); + } + @ExceptionHandler(ResourceAccessException.class) public ResponseEntity> serverUnreachable(ResourceAccessException e) { + if (RequestTimeouts.isTimeout(e)) { + LOGGER.warn("MediaGarrd server did not respond in time: {}", e.getMessage()); + return error(HttpStatus.GATEWAY_TIMEOUT, "MediaGarrd server did not respond in time"); + } LOGGER.warn("MediaGarrd server unreachable: {}", e.getMessage()); - return e.getCause() instanceof HttpTimeoutException || e.getCause() instanceof SocketTimeoutException - ? error(HttpStatus.GATEWAY_TIMEOUT, "MediaGarrd server did not respond in time") - : error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); + return error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); } @ExceptionHandler(ResponseStatusException.class) diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java index 87ea9ae..f1ea456 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -3,8 +3,6 @@ import java.net.URI; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -15,13 +13,14 @@ import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; -import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; +import wellatleastitried.mediagarrdclient.dto.DashboardState; import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; import wellatleastitried.mediagarrdclient.service.BackupPickupService; import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; import wellatleastitried.mediagarrdclient.service.ServerApiService; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; @@ -29,31 +28,36 @@ @RequestMapping("/api/client") public class ClientController { - private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class); - private final ClientStateService stateService; private final ServerDiscoveryService discoveryService; private final ServerApiService serverApiService; private final BackupPickupService pickupService; + private final DashboardService dashboardService; public ClientController( ClientStateService stateService, ServerDiscoveryService discoveryService, ServerApiService serverApiService, - BackupPickupService pickupService + BackupPickupService pickupService, + DashboardService dashboardService ) { this.stateService = stateService; this.discoveryService = discoveryService; this.serverApiService = serverApiService; this.pickupService = pickupService; + this.dashboardService = dashboardService; } @GetMapping("/status") public ClientStatusDto status() { - discoveryService.connectPreferredServer(); return currentStatus(); } + @GetMapping("/dashboard") + public DashboardState dashboard() { + return dashboardService.state(); + } + @PostMapping("/discover") public List discover() { List discovered = discoveryService.discover(); @@ -61,20 +65,6 @@ public List discover() { return discovered; } - @GetMapping("/server-health") - public ConnectionStatusDto serverHealth() { - String activeServer = stateService.getActiveServer(); - if (isBlank(activeServer)) { - return new ConnectionStatusDto("", false); - } - try { - return new ConnectionStatusDto(activeServer, true, serverApiService.health(activeServer)); - } catch (RuntimeException e) { - LOGGER.debug("{} is unreachable: {}", activeServer, e.getMessage()); - return new ConnectionStatusDto(activeServer, false); - } - } - @PutMapping("/server") public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { if (!isBlank(request.serverUrl())) { diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java new file mode 100644 index 0000000..cb8d71f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java @@ -0,0 +1,46 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.AsyncRequestNotUsableException; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdclient.service.DashboardService; + +@RestController +@RequestMapping("/api/client") +public class ClientEventsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventsController.class); + + private final DashboardService dashboard; + + public ClientEventsController(DashboardService dashboard) { + this.dashboard = dashboard; + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity events() { + return dashboard.subscribe() + .map(emitter -> ResponseEntity.ok() + .cacheControl(CacheControl.noCache()) + .header("X-Accel-Buffering", "no") + .body(emitter)) + .orElseGet(() -> ResponseEntity.status(503).build()); + } + + @ExceptionHandler({IOException.class, AsyncRequestNotUsableException.class, AsyncRequestTimeoutException.class}) + public void streamEnded(Exception e) { + LOGGER.debug("Browser event stream ended: {}", e.getMessage()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java index 6b83040..798318a 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java @@ -3,11 +3,13 @@ public enum Endpoints { SERVER_HEALTH("/api/v1/health"), + SERVER_VERSION("/api/v1/version"), SERVER_BACKUPS("/api/v1/backups"), SERVER_BACKUP_RUN("/api/v1/backups/run"), SERVER_SCHEDULE("/api/v1/schedule"), SERVER_CONFIG("/api/v1/config"), - SERVER_SERVICES("/api/v1/services"); + SERVER_SERVICES("/api/v1/services"), + SERVER_EVENTS("/api/v1/events"); private final String path; diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java new file mode 100644 index 0000000..d6ca709 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum CheckState { + NOT_CHECKED, + OK, + NO_RELEASES, + UNAVAILABLE, + ERROR +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java deleted file mode 100644 index 6c6631d..0000000 --- a/src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java +++ /dev/null @@ -1,7 +0,0 @@ -package wellatleastitried.mediagarrdclient.dto; - -public record ConnectionStatusDto(String activeServer, boolean connected, ServerStatusDto serverStatus) { - public ConnectionStatusDto(String activeServer, boolean connected) { - this(activeServer, connected, null); - } -} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java new file mode 100644 index 0000000..b961cec --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.util.List; + +public record DashboardState( + String activeServer, + List knownServers, + LinkState link, + Boolean running, + HealthSummary health, + VersionsDto versions +) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java new file mode 100644 index 0000000..65d029a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Duration; + +public record HealthSummary(Duration backupInterval, int backupRetentionCount) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java new file mode 100644 index 0000000..5ad4e28 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum LinkState { + LIVE, + CONNECTING, + DEGRADED, + DOWN +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java new file mode 100644 index 0000000..04a3d30 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Instant; + +public record VersionStatusDto( + String currentVersion, + String latestVersion, + String releaseUrl, + boolean updateAvailable, + CheckState checkState, + Instant checkedAt, + String message +) {} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java new file mode 100644 index 0000000..28c69a5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java @@ -0,0 +1,3 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record VersionsDto(VersionStatusDto client, VersionStatusDto server) {} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java new file mode 100644 index 0000000..0325aaf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class BackupRunTimeoutException extends RuntimeException { + + public BackupRunTimeoutException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java new file mode 100644 index 0000000..f9c0afa --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.service; + +public record ClientEvent(String name, String data) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java new file mode 100644 index 0000000..15d38e1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java @@ -0,0 +1,198 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.LongFunction; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + + +import jakarta.annotation.PreDestroy; + +@Service +public class ClientEventBroadcaster { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventBroadcaster.class); + private static final Duration PING_INTERVAL = Duration.ofSeconds(20); + private static final Duration STREAM_LIFETIME = Duration.ofSeconds(270); + private static final Duration EMITTER_TIMEOUT = Duration.ofMinutes(6); + private static final int MAX_SUBSCRIBERS = 32; + private static final int QUEUE_CAPACITY = 64; + private static final long RETRY_MILLIS = 5000; + private static final String PING_DATA = "{}"; + + private static final ClientEvent PING = new ClientEvent("ping", PING_DATA); + private static final ClientEvent CLOSE = new ClientEvent("close", ""); + + private final class Subscriber { + + private final SseEmitter emitter; + private final BlockingQueue queue = new LinkedBlockingQueue<>(queueCapacity); + private volatile boolean closed; + + private Subscriber(SseEmitter emitter) { + this.emitter = emitter; + } + + private boolean offer(ClientEvent message) { + return !closed && queue.offer(message); + } + + private void close() { + closed = true; + queue.offer(CLOSE); + } + + private void run() { + boolean failed = false; + boolean first = true; + long deadline = System.nanoTime() + streamLifetime.toNanos(); + try { + while (!closed) { + long remainingMillis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMillis <= 0) { + break; + } + ClientEvent polled = queue.poll(Math.min(pingInterval.toMillis(), remainingMillis), TimeUnit.MILLISECONDS); + if (closed || polled == CLOSE) { + break; + } + if (polled == null && System.nanoTime() >= deadline) { + break; + } + ClientEvent message = polled == null ? PING : polled; + SseEmitter.SseEventBuilder event = SseEmitter.event(); + if (first) { + event.reconnectTime(RETRY_MILLIS); + first = false; + } + emitter.send(event.name(message.name()).data(message.data())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + failed = true; + LOGGER.debug("Browser event stream ended: {}", e.getMessage()); + } finally { + detach(this); + if (!failed) { + try { + emitter.complete(); + } catch (RuntimeException e) { + LOGGER.debug("Completing browser event stream failed: {}", e.getMessage()); + } + } + } + } + } + + private final Duration pingInterval; + private final int maxSubscribers; + private final int queueCapacity; + private final Duration streamLifetime; + private final long emitterTimeoutMillis; + private final ThreadFactory threadFactory; + private final LongFunction emitterFactory; + private final Object lock = new Object(); + private final List subscribers = new ArrayList<>(); + private boolean shutdown; + + @Autowired + public ClientEventBroadcaster() { + this(PING_INTERVAL, MAX_SUBSCRIBERS, QUEUE_CAPACITY, STREAM_LIFETIME, EMITTER_TIMEOUT, writerThreads(), SseEmitter::new); + } + + ClientEventBroadcaster( + Duration pingInterval, + int maxSubscribers, + int queueCapacity, + Duration streamLifetime, + Duration emitterTimeout, + ThreadFactory threadFactory, + LongFunction emitterFactory + ) { + this.pingInterval = pingInterval; + this.maxSubscribers = maxSubscribers; + this.queueCapacity = queueCapacity; + this.streamLifetime = streamLifetime; + this.emitterTimeoutMillis = emitterTimeout.toMillis(); + this.threadFactory = threadFactory; + this.emitterFactory = emitterFactory; + } + + private static ThreadFactory writerThreads() { + AtomicInteger counter = new AtomicInteger(); + return runnable -> Thread.ofPlatform().daemon().name("client-events-writer-" + counter.incrementAndGet()).unstarted(runnable); + } + + public Optional subscribe(List initial) { + SseEmitter emitter = emitterFactory.apply(emitterTimeoutMillis); + Subscriber subscriber = new Subscriber(emitter); + Thread writer = threadFactory.newThread(subscriber::run); + synchronized (lock) { + if (shutdown || subscribers.size() >= maxSubscribers) { + return Optional.empty(); + } + subscribers.add(subscriber); + initial.forEach(subscriber::offer); + } + emitter.onCompletion(() -> detach(subscriber)); + emitter.onTimeout(() -> detach(subscriber)); + emitter.onError(error -> detach(subscriber)); + writer.start(); + return Optional.of(emitter); + } + + public void publish(String name, String data) { + synchronized (lock) { + broadcast(new ClientEvent(name, data)); + } + } + + public int subscriberCount() { + synchronized (lock) { + return subscribers.size(); + } + } + + @PreDestroy + void shutdown() { + synchronized (lock) { + shutdown = true; + subscribers.forEach(Subscriber::close); + subscribers.clear(); + } + } + + private void broadcast(ClientEvent message) { + Iterator iterator = subscribers.iterator(); + while (iterator.hasNext()) { + Subscriber subscriber = iterator.next(); + if (!subscriber.offer(message)) { + LOGGER.warn("Dropping a browser event subscriber that is not keeping up"); + subscriber.close(); + iterator.remove(); + } + } + } + + private void detach(Subscriber subscriber) { + synchronized (lock) { + subscribers.remove(subscriber); + } + subscriber.close(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java index 258c718..d6cb990 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -8,7 +8,10 @@ import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,6 +37,8 @@ record ClientState(String activeServer, long pickupIntervalSeconds, List private final Path statePath; private final ObjectMapper mapper; private final Set knownServers = new LinkedHashSet<>(); + private final List> activeServerListeners = new CopyOnWriteArrayList<>(); + private final List knownServersListeners = new CopyOnWriteArrayList<>(); private String activeServer; private Duration pickupInterval; @@ -64,25 +69,110 @@ public synchronized List getKnownServers() { return List.copyOf(knownServers); } - public synchronized void updateKnownServers(List servers) { - knownServers.clear(); - knownServers.addAll(servers); - if (isBlank(activeServer)) { - activeServer = knownServers.stream().findFirst().orElse(null); - } else { - knownServers.add(activeServer); + public void updateKnownServers(List servers) { + String before = null; + String after = null; + List listBefore = null; + List listAfter = null; + try { + synchronized (this) { + before = activeServer; + listBefore = List.copyOf(knownServers); + knownServers.clear(); + knownServers.addAll(servers); + if (isBlank(activeServer)) { + activeServer = knownServers.stream().findFirst().orElse(null); + } else { + knownServers.add(activeServer); + } + after = activeServer; + listAfter = List.copyOf(knownServers); + LOGGER.info("Known servers updated: {}, active server: {}", knownServers, activeServer); + save(); + } + } finally { + if (!Objects.equals(before, after)) { + notifyActiveServerListeners(after); + } + if (listBefore != null && !listBefore.equals(listAfter)) { + notifyKnownServersListeners(); + } } - LOGGER.info("Known servers updated: {}, active server: {}", knownServers, activeServer); - save(); } - public synchronized void setActiveServer(String serverUrl) { - LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); - activeServer = serverUrl; - if (!isBlank(serverUrl)) { - knownServers.add(serverUrl); + public void setActiveServer(String serverUrl) { + boolean changed = false; + boolean listChanged = false; + try { + synchronized (this) { + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + changed = !Objects.equals(activeServer, serverUrl); + activeServer = serverUrl; + if (!isBlank(serverUrl)) { + listChanged = knownServers.add(serverUrl); + } + save(); + } + } finally { + if (changed) { + notifyActiveServerListeners(serverUrl); + } + if (listChanged) { + notifyKnownServersListeners(); + } + } + } + + public void setActiveServerIfBlank(String serverUrl) { + boolean changed = false; + boolean listChanged = false; + try { + synchronized (this) { + if (!isBlank(activeServer) || isBlank(serverUrl)) { + return; + } + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + activeServer = serverUrl; + changed = true; + listChanged = knownServers.add(serverUrl); + save(); + } + } finally { + if (changed) { + notifyActiveServerListeners(serverUrl); + } + if (listChanged) { + notifyKnownServersListeners(); + } + } + } + + public void addActiveServerListener(Consumer listener) { + activeServerListeners.add(listener); + } + + public void addKnownServersListener(Runnable listener) { + knownServersListeners.add(listener); + } + + private void notifyKnownServersListeners() { + for (Runnable listener : knownServersListeners) { + try { + listener.run(); + } catch (RuntimeException e) { + LOGGER.warn("Known servers listener failed: {}", e.getMessage()); + } + } + } + + private void notifyActiveServerListeners(String serverUrl) { + for (Consumer listener : activeServerListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Active server listener failed: {}", e.getMessage()); + } } - save(); } public synchronized Duration setPickupInterval(Duration interval) { diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java new file mode 100644 index 0000000..a20689b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java @@ -0,0 +1,426 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; + +@Service +public class DashboardService { + + private static final Logger LOGGER = LoggerFactory.getLogger(DashboardService.class); + private static final Duration POLL_INTERVAL = Duration.ofSeconds(7); + private static final Duration CATCH_ALL_INTERVAL = Duration.ofSeconds(60); + + private final class Refresh { + + private final Runnable work; + private boolean inFlight; + private boolean again; + + private Refresh(Runnable work) { + this.work = work; + } + + private void request() { + synchronized (lock) { + if (inFlight) { + again = true; + return; + } + inFlight = true; + } + try { + executor.execute(this::loop); + } catch (RejectedExecutionException e) { + synchronized (lock) { + inFlight = false; + } + } + } + + private void loop() { + boolean repeat; + do { + try { + work.run(); + } catch (RuntimeException e) { + LOGGER.warn("Dashboard refresh failed: {}", e.getMessage()); + } + synchronized (lock) { + repeat = again; + again = false; + if (!repeat) { + inFlight = false; + } + } + } while (repeat); + } + + private boolean busy() { + return inFlight; + } + } + + private final ClientStateService stateService; + private final ClientEventBroadcaster broadcaster; + private final ServerApiService serverApiService; + private final VersionService versionService; + private final UpdateCheckService updateCheckService; + private final ObjectMapper mapper; + private final Executor executor; + private final Clock clock; + private final Object lock = new Object(); + private final Refresh healthRefresh = new Refresh(this::fetchHealth); + private final Refresh versionRefresh = new Refresh(this::fetchVersion); + private final Refresh backupsRefresh = new Refresh(this::fetchBackups); + private String activeServer; + private List knownServers = List.of(); + private LinkState link = LinkState.DOWN; + private Boolean running; + private HealthSummary health; + private Instant healthFetchedAt; + private List backupsSeen; + private Instant backupsCheckedAt; + private long epoch; + + @Autowired + public DashboardService( + ClientStateService stateService, + ClientEventBroadcaster broadcaster, + ServerApiService serverApiService, + VersionService versionService, + UpdateCheckService updateCheckService, + ObjectMapper mapper + ) { + this(stateService, broadcaster, serverApiService, versionService, updateCheckService, mapper, refreshThreads(), Clock.systemUTC()); + } + + DashboardService( + ClientStateService stateService, + ClientEventBroadcaster broadcaster, + ServerApiService serverApiService, + VersionService versionService, + UpdateCheckService updateCheckService, + ObjectMapper mapper, + Executor executor, + Clock clock + ) { + this.stateService = stateService; + this.broadcaster = broadcaster; + this.serverApiService = serverApiService; + this.versionService = versionService; + this.updateCheckService = updateCheckService; + this.mapper = mapper; + this.executor = executor; + this.clock = clock; + } + + private static ExecutorService refreshThreads() { + AtomicInteger counter = new AtomicInteger(); + return Executors.newFixedThreadPool(2, runnable -> Thread.ofPlatform().daemon().name("dashboard-refresh-" + counter.incrementAndGet()).unstarted(runnable)); + } + + @PostConstruct + void start() { + stateService.addKnownServersListener(this::sync); + updateCheckService.addStatusListener(ignored -> publishVersions()); + sync(); + } + + @PreDestroy + void shutdown() { + if (executor instanceof ExecutorService service) { + service.shutdownNow(); + } + } + + public DashboardState state() { + synchronized (lock) { + return snapshot(); + } + } + + public Optional subscribe() { + synchronized (lock) { + return broadcaster.subscribe(List.of(new ClientEvent("snapshot", json(snapshot())))); + } + } + + void sync() { + synchronized (lock) { + String active = normalize(stateService.getActiveServer()); + List known = stateService.getKnownServers(); + if (!Objects.equals(active, activeServer)) { + activeServer = active; + knownServers = known; + link = active == null ? LinkState.DOWN : LinkState.CONNECTING; + running = null; + health = null; + healthFetchedAt = null; + backupsSeen = null; + backupsCheckedAt = null; + epoch++; + versionService.select(active); + broadcaster.publish("snapshot", json(snapshot())); + if (active != null) { + healthRefresh.request(); + } + } else if (!known.equals(knownServers)) { + knownServers = known; + publishServers(); + } + } + } + + void streamUp(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + boolean wasDown = link == LinkState.DOWN; + setLink(LinkState.LIVE); + healthRefresh.request(); + if (versionService.invalidate(wasDown)) { + versionRefresh.request(); + } + } + } + + void streamDown(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + setLink(LinkState.CONNECTING); + healthRefresh.request(); + } + } + + void runEvent(String server, String name, String data, boolean runningNow) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + running = runningNow; + broadcaster.publish(name, data); + } + } + + void backupsChanged(String server, String data) { + synchronized (lock) { + if (Objects.equals(server, activeServer)) { + broadcaster.publish("backups-changed", data); + } + } + } + + void configChanged(String server) { + synchronized (lock) { + if (Objects.equals(server, activeServer)) { + healthRefresh.request(); + } + } + } + + @Scheduled(initialDelayString = "PT8S", fixedDelayString = "PT8S") + void tick() { + synchronized (lock) { + if (activeServer == null) { + return; + } + Duration limit = link == LinkState.LIVE ? CATCH_ALL_INTERVAL : POLL_INTERVAL; + boolean due = healthFetchedAt == null || Duration.between(healthFetchedAt, clock.instant()).compareTo(limit) >= 0; + if (due && !healthRefresh.busy()) { + healthRefresh.request(); + } + if (reachable() && !versionRefresh.busy() && versionService.needsRefresh()) { + versionRefresh.request(); + } + if (link == LinkState.DEGRADED && !backupsRefresh.busy() && (backupsCheckedAt == null || Duration.between(backupsCheckedAt, clock.instant()).compareTo(CATCH_ALL_INTERVAL) >= 0)) { + backupsRefresh.request(); + } + } + } + + private void fetchHealth() { + String server; + long expected; + synchronized (lock) { + server = activeServer; + expected = epoch; + } + if (server == null) { + return; + } + ServerStatusDto status = null; + try { + status = serverApiService.health(server); + } catch (RuntimeException e) { + LOGGER.debug("{} did not answer the health check: {}", server, e.getMessage()); + } + applyHealth(expected, status); + } + + private void applyHealth(long expected, ServerStatusDto status) { + synchronized (lock) { + if (expected != epoch) { + return; + } + healthFetchedAt = clock.instant(); + if (status == null) { + if (link != LinkState.LIVE) { + setLink(LinkState.DOWN); + if (versionService.markUnreachable()) { + broadcaster.publish("versions", json(versionService.versions())); + } + } + return; + } + HealthSummary summary = new HealthSummary(status.backupInterval(), status.backupRetentionCount()); + if (!summary.equals(health)) { + health = summary; + broadcaster.publish("config", json(summary)); + } + if (link != LinkState.LIVE) { + boolean recovered = link != LinkState.DEGRADED; + boolean wasDown = link == LinkState.DOWN; + setLink(LinkState.DEGRADED); + setPolledRunning(status.running()); + if (recovered && versionService.invalidate(wasDown)) { + versionRefresh.request(); + } + } + } + } + + private void fetchBackups() { + String server; + long expected; + synchronized (lock) { + server = activeServer; + expected = epoch; + } + if (server == null) { + return; + } + List listed; + try { + listed = serverApiService.listBackups(server); + } catch (RuntimeException e) { + LOGGER.debug("{} did not list its backups: {}", server, e.getMessage()); + listed = null; + } + synchronized (lock) { + if (expected != epoch || link != LinkState.DEGRADED) { + return; + } + backupsCheckedAt = clock.instant(); + if (listed == null) { + return; + } + if (backupsSeen != null && !listed.equals(backupsSeen)) { + broadcaster.publish("backups-changed", json(Map.of("at", clock.instant().toString()))); + } + backupsSeen = listed; + } + } + + private boolean reachable() { + return link == LinkState.LIVE || link == LinkState.DEGRADED; + } + + private void fetchVersion() { + if (versionService.refresh()) { + publishVersions(); + } + } + + private void publishVersions() { + synchronized (lock) { + broadcaster.publish("versions", json(versionService.versions())); + } + } + + private void publishServers() { + Map payload = new LinkedHashMap<>(); + payload.put("knownServers", knownServers); + payload.put("activeServer", activeServer); + broadcaster.publish("servers", json(payload)); + } + + private void setLink(LinkState next) { + if (link == next) { + return; + } + link = next; + if (!reachable()) { + running = null; + } + if (next != LinkState.DEGRADED) { + backupsSeen = null; + backupsCheckedAt = null; + } + Map payload = new LinkedHashMap<>(); + payload.put("server", activeServer == null ? "" : activeServer); + payload.put("state", next); + broadcaster.publish("link", json(payload)); + } + + private void setPolledRunning(boolean polled) { + if (Boolean.valueOf(polled).equals(running)) { + return; + } + if (Boolean.TRUE.equals(running) && !polled) { + backupsSeen = null; + } + running = polled; + Map payload = new LinkedHashMap<>(); + payload.put("running", polled); + payload.put("at", clock.instant().toString()); + broadcaster.publish("state", json(payload)); + } + + private DashboardState snapshot() { + return new DashboardState(activeServer, knownServers, link, running, health, versionService.versions()); + } + + private String json(Object payload) { + try { + return mapper.writeValueAsString(payload); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); + } + } + + private static String normalize(String url) { + return url == null || url.isBlank() ? null : url; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java b/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java new file mode 100644 index 0000000..5c02ce1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java @@ -0,0 +1,37 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.SocketTimeoutException; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpTimeoutException; +import java.util.concurrent.TimeoutException; + +public final class RequestTimeouts { + + private static final int MAX_DEPTH = 16; + + private RequestTimeouts() { + } + + public static boolean isTimeout(Throwable e) { + int depth = 0; + for (Throwable t = e; t != null && depth++ < MAX_DEPTH; t = t.getCause()) { + if (t instanceof HttpTimeoutException || t instanceof SocketTimeoutException || t instanceof TimeoutException) { + return true; + } + } + return false; + } + + public static boolean isReadTimeout(Throwable e) { + int depth = 0; + for (Throwable t = e; t != null && depth++ < MAX_DEPTH; t = t.getCause()) { + if (t instanceof HttpConnectTimeoutException) { + return false; + } + if (t instanceof HttpTimeoutException || t instanceof SocketTimeoutException || t instanceof TimeoutException) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java new file mode 100644 index 0000000..7ee55da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java @@ -0,0 +1,78 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public record SemVer(long major, long minor, long patch, List prerelease) implements Comparable { + + private static final String IDENTIFIERS = "[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*"; + private static final Pattern PATTERN = Pattern.compile( + "v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-(" + IDENTIFIERS + "))?(?:\\+" + IDENTIFIERS + ")?"); + + public static Optional parse(String text) { + if (text == null) { + return Optional.empty(); + } + Matcher matcher = PATTERN.matcher(text.strip()); + if (!matcher.matches()) { + return Optional.empty(); + } + try { + List prerelease = matcher.group(4) == null ? List.of() : Arrays.asList(matcher.group(4).split("\\.")); + return Optional.of(new SemVer( + Long.parseLong(matcher.group(1)), + Long.parseLong(matcher.group(2)), + Long.parseLong(matcher.group(3)), + prerelease)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + @Override + public int compareTo(SemVer other) { + int result = Long.compare(major, other.major); + if (result == 0) { + result = Long.compare(minor, other.minor); + } + if (result == 0) { + result = Long.compare(patch, other.patch); + } + return result != 0 ? result : comparePrerelease(prerelease, other.prerelease); + } + + @Override + public String toString() { + String core = major + "." + minor + "." + patch; + return prerelease.isEmpty() ? core : core + "-" + String.join(".", prerelease); + } + + private static int comparePrerelease(List left, List right) { + if (left.isEmpty() || right.isEmpty()) { + return Boolean.compare(left.isEmpty(), right.isEmpty()); + } + for (int i = 0; i < Math.min(left.size(), right.size()); i++) { + int result = compareIdentifier(left.get(i), right.get(i)); + if (result != 0) { + return result; + } + } + return Integer.compare(left.size(), right.size()); + } + + private static int compareIdentifier(String left, String right) { + boolean leftNumeric = left.chars().allMatch(Character::isDigit); + boolean rightNumeric = right.chars().allMatch(Character::isDigit); + if (leftNumeric && rightNumeric) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + if (leftNumeric != rightNumeric) { + return leftNumeric ? -1 : 1; + } + return left.compareTo(right); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java index f6db95b..afa9eb8 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -18,18 +18,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import org.springframework.http.client.JdkClientHttpRequestFactory; import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClient; import org.springframework.web.util.UriUtils; +import wellatleastitried.mediagarrdclient.Configuration; import wellatleastitried.mediagarrdclient.api.Endpoints; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; @Service public class ServerApiService { @@ -44,6 +48,7 @@ public interface DownloadProgressListener { private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(5); private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30); + static final Duration MIN_BACKUP_RUN_TIMEOUT = Duration.ofMinutes(1); private static final int BUFFER_SIZE = 64 * 1024; private final HttpClient httpClient = HttpClient.newBuilder() @@ -52,7 +57,25 @@ public interface DownloadProgressListener { .build(); private final RestClient healthClient = restClient(HEALTH_TIMEOUT); private final RestClient restClient = restClient(REQUEST_TIMEOUT); - private final RestClient backupRunClient = restClient(null); + private final RestClient backupRunClient; + private final Duration backupRunTimeout; + + @Autowired + public ServerApiService(Configuration properties) { + this(checked(properties.getBackupRunTimeout())); + } + + private static Duration checked(Duration backupRunTimeout) { + if (backupRunTimeout == null || backupRunTimeout.compareTo(MIN_BACKUP_RUN_TIMEOUT) < 0) { + throw new IllegalStateException("mediagarrd.client.backup-run-timeout must be at least " + MIN_BACKUP_RUN_TIMEOUT + ", was " + backupRunTimeout); + } + return backupRunTimeout; + } + + ServerApiService(Duration backupRunTimeout) { + this.backupRunTimeout = backupRunTimeout; + this.backupRunClient = restClient(backupRunTimeout); + } private RestClient restClient(Duration readTimeout) { JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); @@ -71,6 +94,13 @@ public ServerStatusDto health(String serverUrl) { return status; } + public VersionStatusDto serverVersion(String serverUrl) { + return healthClient.get() + .uri(serverUrl + Endpoints.SERVER_VERSION.getPath()) + .retrieve() + .body(VersionStatusDto.class); + } + public List listBackups(String serverUrl) { List backups = restClient.get() .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) @@ -82,10 +112,19 @@ public List listBackups(String serverUrl) { public void triggerBackup(String serverUrl) { LOGGER.info("Triggering backup on {}", serverUrl); - backupRunClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() - .toBodilessEntity(); + try { + backupRunClient.post() + .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) + .retrieve() + .toBodilessEntity(); + } catch (ResourceAccessException e) { + if (RequestTimeouts.isReadTimeout(e)) { + LOGGER.warn("Backup on {} did not finish within {}", serverUrl, backupRunTimeout); + throw new BackupRunTimeoutException("The backup did not finish within " + backupRunTimeout + + " and is probably still running on the server. The dashboard's live status shows when it finishes.", e); + } + throw e; + } LOGGER.info("Backup finished on {}", serverUrl); } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java index ed9fbdd..83b35db 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -24,12 +24,19 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @@ -53,6 +60,10 @@ public class ServerDiscoveryService { private static final int MAX_CONCURRENT_PROBES = 256; private static final Duration CONNECT_TIMEOUT = Duration.ofMillis(500); private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(2); + static final Duration PREFERRED_ATTEMPT_DEADLINE = Duration.ofSeconds(3); + private static final int ATTEMPT_PENDING = 0; + private static final int ATTEMPT_RUNNING = 1; + private static final int ATTEMPT_ABANDONED = 2; private static final Duration SCAN_DEADLINE = Duration.ofSeconds(20); enum Probe { OPEN, REFUSED, UNREACHABLE } @@ -79,20 +90,64 @@ private record QuickResult(Optional server, boolean hostAlive) { .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) .followRedirects(HttpClient.Redirect.NEVER) .build(); - private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final ExecutorService executor; + private final Duration preferredDeadline; + private final AtomicBoolean preferredAttempt = new AtomicBoolean(); private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES); + @Autowired public ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper) { + this(configuration, stateService, mapper, Executors.newVirtualThreadPerTaskExecutor(), PREFERRED_ATTEMPT_DEADLINE); + } + + ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper, ExecutorService executor, Duration preferredDeadline) { + this.executor = executor; + this.preferredDeadline = preferredDeadline; this.configuration = configuration; this.stateService = stateService; this.mapper = mapper; } - @Scheduled(fixedDelay = 30_000) + @Scheduled(initialDelay = 1_000, fixedDelay = 4_000) public void connectPreferredServer() { String active = stateService.getActiveServer(); - if (active == null || active.isBlank()) { - resolvePreferredServer().ifPresent(stateService::setActiveServer); + if ((active != null && !active.isBlank()) || !preferredAttempt.compareAndSet(false, true)) { + return; + } + AtomicInteger phase = new AtomicInteger(ATTEMPT_PENDING); + Future> attempt; + try { + attempt = executor.submit(() -> { + if (!phase.compareAndSet(ATTEMPT_PENDING, ATTEMPT_RUNNING)) { + return Optional.empty(); + } + try { + return resolvePreferredServer(); + } finally { + preferredAttempt.set(false); + } + }); + } catch (RuntimeException e) { + preferredAttempt.set(false); + return; + } + try { + attempt.get(preferredDeadline.toMillis(), TimeUnit.MILLISECONDS).ifPresent(stateService::setActiveServerIfBlank); + } catch (TimeoutException e) { + abandon(attempt, phase); + LOGGER.debug("Resolving the preferred server took longer than {} ms, retrying on the next tick", preferredDeadline.toMillis()); + } catch (ExecutionException e) { + LOGGER.debug("Resolving the preferred server failed: {}", e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); + } catch (InterruptedException e) { + abandon(attempt, phase); + Thread.currentThread().interrupt(); + } + } + + private void abandon(Future attempt, AtomicInteger phase) { + attempt.cancel(true); + if (phase.compareAndSet(ATTEMPT_PENDING, ATTEMPT_ABANDONED)) { + preferredAttempt.set(false); } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java new file mode 100644 index 0000000..02a0711 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java @@ -0,0 +1,375 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.api.Endpoints; + +@Service +public class ServerEventStreamService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerEventStreamService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration HEADER_TIMEOUT = Duration.ofSeconds(10); + private static final Duration WATCHDOG = Duration.ofSeconds(45); + private static final Duration INITIAL_BACKOFF = Duration.ofSeconds(1); + private static final Duration MAX_BACKOFF = Duration.ofSeconds(30); + private static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5); + private static final Duration MIN_STREAM_LIFETIME = Duration.ofSeconds(5); + private static final Set FORWARDED_EVENTS = Set.of("state", "run-started", "run-finished", "backups-changed", "config-changed"); + + public record Timing(Duration headerTimeout, Duration watchdog, Duration initialBackoff, Duration maxBackoff, Duration unsupportedRetry, Duration minStreamLifetime) { + } + + private enum Outcome { + ROLLOVER, + UNSUPPORTED, + FAILED + } + + private final class Stream implements Runnable { + + private final String serverUrl; + private final CountDownLatch cancelled = new CountDownLatch(1); + private volatile CompletableFuture> pending; + private volatile InputStream body; + private volatile long lastActivityNanos; + private boolean linkUp; + private boolean eventsSeen; + private Thread thread; + + private Stream(String serverUrl) { + this.serverUrl = serverUrl; + } + + private boolean isCancelled() { + return cancelled.getCount() == 0; + } + + private void cancel() { + cancelled.countDown(); + CompletableFuture> future = pending; + if (future != null) { + future.cancel(true); + } + closeBody(); + Thread worker = thread; + if (worker != null) { + worker.interrupt(); + } + } + + private void closeBody() { + InputStream stream = body; + if (stream != null) { + try { + stream.close(); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Closing event stream failed: {}", e.getMessage()); + } + } + } + + private boolean pause(Duration delay) { + try { + return cancelled.await(delay.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + return true; + } + } + + @Override + public void run() { + Duration backoff = timing.initialBackoff(); + try { + while (!isCancelled()) { + Outcome outcome; + long startedNanos = System.nanoTime(); + try { + outcome = connectAndRead(); + } catch (RuntimeException e) { + LOGGER.warn("Event stream of {} failed: {}", serverUrl, e.getMessage()); + outcome = Outcome.FAILED; + } + if (isCancelled()) { + break; + } + boolean shortLived = System.nanoTime() - startedNanos < timing.minStreamLifetime().toNanos(); + if (eventsSeen) { + eventsSeen = false; + if (!shortLived) { + backoff = timing.initialBackoff(); + } + } + if (outcome == Outcome.ROLLOVER && shortLived) { + outcome = Outcome.FAILED; + } + if (outcome == Outcome.ROLLOVER) { + continue; + } + reportLink(false); + Duration delay = outcome == Outcome.UNSUPPORTED ? timing.unsupportedRetry() : backoff; + if (outcome == Outcome.FAILED) { + backoff = min(backoff.multipliedBy(2), timing.maxBackoff()); + } + if (pause(delay)) { + break; + } + } + } finally { + closeBody(); + } + } + + private Outcome connectAndRead() { + HttpRequest request = HttpRequest.newBuilder(URI.create(serverUrl + Endpoints.SERVER_EVENTS.getPath())) + .timeout(timing.headerTimeout()) + .header("Accept", "text/event-stream") + .GET() + .build(); + CompletableFuture> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()); + pending = future; + if (isCancelled()) { + future.cancel(true); + return Outcome.FAILED; + } + HttpResponse response; + try { + response = future.get(); + } catch (InterruptedException | CancellationException e) { + return Outcome.FAILED; + } catch (ExecutionException e) { + LOGGER.debug("Could not open event stream of {}: {}", serverUrl, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); + return Outcome.FAILED; + } + body = response.body(); + if (isCancelled()) { + closeBody(); + return Outcome.FAILED; + } + int status = response.statusCode(); + if (status == 404) { + closeBody(); + LOGGER.info("{} has no event stream, falling back to polling and retrying in {}", serverUrl, timing.unsupportedRetry()); + return Outcome.UNSUPPORTED; + } + String contentType = response.headers().firstValue("Content-Type").orElse(""); + if (status / 100 != 2 || !contentType.toLowerCase().startsWith("text/event-stream")) { + closeBody(); + LOGGER.debug("Event stream of {} answered {} {}", serverUrl, status, contentType); + return Outcome.FAILED; + } + return read(response.body()); + } + + private Outcome read(InputStream input) { + lastActivityNanos = System.nanoTime(); + ScheduledFuture watchdog = scheduler.scheduleWithFixedDelay(this::checkWatchdog, checkPeriodMillis(), checkPeriodMillis(), TimeUnit.MILLISECONDS); + boolean sawEvent = false; + String name = null; + StringBuilder data = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + lastActivityNanos = System.nanoTime(); + if (line.isEmpty()) { + if (data.length() > 0) { + if (!sawEvent) { + sawEvent = true; + eventsSeen = true; + reportLink(true); + } + dispatch(name == null ? "message" : name, data.toString()); + } + name = null; + data.setLength(0); + } else if (line.startsWith(":")) { + continue; + } else { + int colon = line.indexOf(':'); + String field = colon < 0 ? line : line.substring(0, colon); + String value = colon < 0 ? "" : line.substring(colon + 1); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (field.equals("event")) { + name = value; + } else if (field.equals("data")) { + if (data.length() > 0) { + data.append('\n'); + } + data.append(value); + } + } + } + return sawEvent ? Outcome.ROLLOVER : Outcome.FAILED; + } catch (IOException | RuntimeException e) { + if (!isCancelled()) { + LOGGER.debug("Event stream of {} ended: {}", serverUrl, e.getMessage()); + } + return Outcome.FAILED; + } finally { + watchdog.cancel(false); + } + } + + private long checkPeriodMillis() { + return Math.max(10, timing.watchdog().toMillis() / 4); + } + + private void checkWatchdog() { + if (System.nanoTime() - lastActivityNanos > timing.watchdog().toNanos()) { + LOGGER.warn("Event stream of {} went quiet for {}, reconnecting", serverUrl, timing.watchdog()); + closeBody(); + } + } + + private void reportLink(boolean connected) { + if (linkUp == connected || isCancelled()) { + return; + } + linkUp = connected; + synchronized (lock) { + if (current == this) { + if (connected) { + dashboard.streamUp(serverUrl); + } else { + dashboard.streamDown(serverUrl); + } + } + } + } + + private void dispatch(String name, String data) { + if (!FORWARDED_EVENTS.contains(name)) { + return; + } + try { + JsonNode node = mapper.readTree(data); + if (name.equals("state") && !node.has("running")) { + return; + } + boolean running = !name.equals("run-finished") && node.path("running").asBoolean(false); + synchronized (lock) { + if (current != this) { + return; + } + switch (name) { + case "backups-changed" -> dashboard.backupsChanged(serverUrl, data); + case "config-changed" -> dashboard.configChanged(serverUrl); + default -> dashboard.runEvent(serverUrl, name, data, running); + } + } + } catch (IOException e) { + LOGGER.debug("Ignoring malformed {} event from {}", name, serverUrl); + } + } + } + + private static Duration min(Duration a, Duration b) { + return a.compareTo(b) <= 0 ? a : b; + } + + private final ClientStateService stateService; + private final DashboardService dashboard; + private final ObjectMapper mapper; + private final Timing timing; + private final HttpClient httpClient = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(CONNECT_TIMEOUT) + .build(); + private final ThreadFactory threadFactory; + private final ScheduledExecutorService scheduler; + private final Object lock = new Object(); + private Stream current; + + @Autowired + public ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper) { + this(stateService, dashboard, mapper, new Timing(HEADER_TIMEOUT, WATCHDOG, INITIAL_BACKOFF, MAX_BACKOFF, UNSUPPORTED_RETRY, MIN_STREAM_LIFETIME)); + } + + ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, Timing timing) { + this.stateService = stateService; + this.dashboard = dashboard; + this.mapper = mapper; + this.timing = timing; + AtomicInteger counter = new AtomicInteger(); + this.threadFactory = runnable -> Thread.ofPlatform().daemon().name("server-event-stream-" + counter.incrementAndGet()).unstarted(runnable); + this.scheduler = Executors.newSingleThreadScheduledExecutor( + runnable -> Thread.ofPlatform().daemon().name("server-event-watchdog").unstarted(runnable)); + } + + @PostConstruct + void start() { + stateService.addActiveServerListener(ignored -> reconcile()); + reconcile(); + } + + void reconcile() { + synchronized (lock) { + String target = normalize(stateService.getActiveServer()); + String running = current == null ? null : current.serverUrl; + if (Objects.equals(target, running)) { + return; + } + if (current != null) { + current.cancel(); + current = null; + } + dashboard.sync(); + if (target != null) { + Stream stream = new Stream(target); + stream.thread = threadFactory.newThread(stream); + current = stream; + stream.thread.start(); + LOGGER.info("Subscribing to live events of {}", target); + } + } + } + + @PreDestroy + void shutdown() { + synchronized (lock) { + if (current != null) { + current.cancel(); + current = null; + } + } + scheduler.shutdownNow(); + httpClient.shutdownNow(); + } + + private static String normalize(String url) { + return url == null || url.isBlank() ? null : url; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java new file mode 100644 index 0000000..f4a5f2d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java @@ -0,0 +1,190 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.http.HttpClient; +import java.time.Clock; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.context.annotation.Lazy; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +@Service +@Lazy(false) +public class UpdateCheckService { + + @JsonIgnoreProperties(ignoreUnknown = true) + record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("html_url") String htmlUrl) { + } + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCheckService.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration READ_TIMEOUT = Duration.ofSeconds(5); + static final Duration MIN_INTERVAL = Duration.ofHours(1); + + private final String currentVersion; + private final Optional current; + private final String repository; + private final Clock clock; + private final RestClient client; + private final AtomicReference status; + private final List> listeners = new CopyOnWriteArrayList<>(); + + @Autowired + public UpdateCheckService(Configuration properties, ObjectProvider buildProperties) { + this(properties, versionOf(buildProperties), Clock.systemUTC()); + } + + UpdateCheckService(Configuration properties, String currentVersion, Clock clock) { + Duration interval = properties.getUpdateCheckInterval(); + if (interval == null || interval.compareTo(MIN_INTERVAL) < 0) { + throw new IllegalStateException("mediagarrd.client.update-check-interval must be at least " + MIN_INTERVAL + ", was " + interval); + } + this.currentVersion = currentVersion; + this.current = SemVer.parse(currentVersion); + this.repository = properties.getUpdateRepository(); + this.clock = clock; + HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + requestFactory.setReadTimeout(READ_TIMEOUT); + this.client = RestClient.builder() + .baseUrl(properties.getGithubApiBaseUrl().replaceAll("/+$", "")) + .requestFactory(requestFactory) + .defaultHeader(HttpHeaders.USER_AGENT, "MediaGarrd-Client/" + (currentVersion == null ? "unknown" : currentVersion)) + .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github+json") + .build(); + this.status = new AtomicReference<>(result(CheckState.NOT_CHECKED, null, null, null)); + } + + public VersionStatusDto status() { + return status.get(); + } + + public void addStatusListener(Consumer listener) { + listeners.add(listener); + } + + @Scheduled(initialDelayString = "PT5S", fixedDelayString = "${mediagarrd.client.update-check-interval:PT24H}") + public void check() { + VersionStatusDto previous = status.get(); + VersionStatusDto next = fetch(); + status.set(next); + logChange(previous, next); + if (changed(previous, next)) { + for (Consumer listener : listeners) { + try { + listener.accept(next); + } catch (RuntimeException e) { + LOGGER.warn("Update status listener failed: {}", e.getMessage()); + } + } + } + } + + private VersionStatusDto fetch() { + if (current.isEmpty()) { + return result(CheckState.ERROR, null, null, "Current version is unknown"); + } + try { + GithubRelease release = client.get() + .uri("/repos/" + repository + "/releases/latest") + .retrieve() + .body(GithubRelease.class); + return fromRelease(release); + } catch (RestClientResponseException e) { + return fromHttpFailure(e); + } catch (ResourceAccessException e) { + LOGGER.debug("GitHub is unreachable", e); + return result(CheckState.ERROR, null, null, "GitHub is unreachable"); + } catch (RuntimeException e) { + LOGGER.debug("Unexpected update check failure", e); + return result(CheckState.ERROR, null, null, "Unexpected response from GitHub"); + } + } + + private VersionStatusDto fromRelease(GithubRelease release) { + Optional latest = release == null ? Optional.empty() : SemVer.parse(release.tagName()); + if (latest.isEmpty()) { + return result(CheckState.ERROR, null, null, "Latest release has an unrecognized version tag"); + } + String url = release.htmlUrl() == null || release.htmlUrl().isBlank() + ? "https://github.com/" + repository + "/releases/tag/" + release.tagName().strip() + : release.htmlUrl(); + return result(CheckState.OK, latest.get(), url, null); + } + + private VersionStatusDto fromHttpFailure(RestClientResponseException e) { + int code = e.getStatusCode().value(); + if (code == HttpStatus.NOT_FOUND.value()) { + return result(CheckState.NO_RELEASES, null, null, null); + } + boolean limitExhausted = code == HttpStatus.FORBIDDEN.value() + && e.getResponseHeaders() != null + && "0".equals(e.getResponseHeaders().getFirst("X-RateLimit-Remaining")); + if (code == HttpStatus.TOO_MANY_REQUESTS.value() || limitExhausted) { + return result(CheckState.ERROR, null, null, "GitHub rate limit reached"); + } + return result(CheckState.ERROR, null, null, "GitHub returned HTTP " + code); + } + + private VersionStatusDto result(CheckState state, SemVer latest, String url, String message) { + boolean update = state == CheckState.OK && latest != null && current.isPresent() && latest.compareTo(current.get()) > 0; + return new VersionStatusDto( + currentVersion, + latest == null ? null : latest.toString(), + url, + update, + state, + state == CheckState.NOT_CHECKED ? null : clock.instant(), + message); + } + + private static boolean changed(VersionStatusDto previous, VersionStatusDto next) { + return previous.checkState() != next.checkState() + || !Objects.equals(previous.latestVersion(), next.latestVersion()) + || !Objects.equals(previous.message(), next.message()); + } + + private static void logChange(VersionStatusDto previous, VersionStatusDto next) { + if (!changed(previous, next)) { + LOGGER.debug("Update check unchanged: {}", next.checkState()); + } else if (next.checkState() == CheckState.ERROR) { + LOGGER.warn("Update check failed: {}", next.message()); + } else if (next.updateAvailable()) { + LOGGER.info("Update available: {} -> {} ({})", next.currentVersion(), next.latestVersion(), next.releaseUrl()); + } else { + LOGGER.info("Update check: {}, running {}", next.checkState(), next.currentVersion()); + } + } + + private static String versionOf(ObjectProvider buildProperties) { + BuildProperties build = buildProperties.getIfAvailable(); + return build == null ? null : build.getVersion(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java new file mode 100644 index 0000000..262a1d1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java @@ -0,0 +1,151 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; + +@Service +public class VersionService { + + private static final Logger LOGGER = LoggerFactory.getLogger(VersionService.class); + static final Duration REFRESH_INTERVAL = Duration.ofHours(1); + static final Duration RETRY_INTERVAL = Duration.ofMinutes(10); + static final Duration PENDING_RETRY_INTERVAL = Duration.ofSeconds(30); + static final Duration ERROR_RETRY_INTERVAL = Duration.ofMinutes(5); + static final Duration RECENT_SUCCESS = Duration.ofMinutes(5); + private static final VersionStatusDto SERVER_UNAVAILABLE = + new VersionStatusDto(null, null, null, false, CheckState.UNAVAILABLE, null, "Server version is unavailable"); + private static final VersionStatusDto SERVER_PENDING = + new VersionStatusDto(null, null, null, false, CheckState.NOT_CHECKED, null, null); + + private final UpdateCheckService updateCheckService; + private final ServerApiService serverApiService; + private final Clock clock; + private final Object lock = new Object(); + private String selected; + private VersionStatusDto server; + private Instant fetchedAt; + private Instant lastSuccess; + + @Autowired + public VersionService(UpdateCheckService updateCheckService, ServerApiService serverApiService) { + this(updateCheckService, serverApiService, Clock.systemUTC()); + } + + VersionService(UpdateCheckService updateCheckService, ServerApiService serverApiService, Clock clock) { + this.updateCheckService = updateCheckService; + this.serverApiService = serverApiService; + this.clock = clock; + } + + public VersionsDto versions() { + synchronized (lock) { + return new VersionsDto(updateCheckService.status(), server); + } + } + + public boolean select(String serverUrl) { + String next = serverUrl == null || serverUrl.isBlank() ? null : serverUrl; + synchronized (lock) { + if (Objects.equals(next, selected)) { + return false; + } + selected = next; + server = next == null ? null : SERVER_PENDING; + fetchedAt = null; + lastSuccess = null; + return true; + } + } + + public boolean invalidate(boolean force) { + synchronized (lock) { + if (selected == null) { + return false; + } + if (!force && lastSuccess != null && Duration.between(lastSuccess, clock.instant()).compareTo(RECENT_SUCCESS) < 0) { + return false; + } + fetchedAt = null; + return true; + } + } + + public boolean markUnreachable() { + synchronized (lock) { + if (selected == null || server != SERVER_PENDING) { + return false; + } + server = SERVER_UNAVAILABLE; + fetchedAt = clock.instant(); + return true; + } + } + + public boolean needsRefresh() { + synchronized (lock) { + if (selected == null) { + return false; + } + if (fetchedAt == null) { + return true; + } + return Duration.between(fetchedAt, clock.instant()).compareTo(limitFor(server)) >= 0; + } + } + + private static Duration limitFor(VersionStatusDto status) { + if (status == null) { + return REFRESH_INTERVAL; + } + return switch (status.checkState()) { + case NOT_CHECKED -> PENDING_RETRY_INTERVAL; + case ERROR -> ERROR_RETRY_INTERVAL; + case UNAVAILABLE -> RETRY_INTERVAL; + default -> REFRESH_INTERVAL; + }; + } + + public boolean refresh() { + String url; + synchronized (lock) { + url = selected; + } + if (url == null) { + return false; + } + VersionStatusDto fetched = fetch(url); + synchronized (lock) { + if (!url.equals(selected)) { + return false; + } + boolean changed = !fetched.equals(server); + server = fetched; + fetchedAt = clock.instant(); + if (fetched.checkState() == CheckState.OK || fetched.checkState() == CheckState.NO_RELEASES) { + lastSuccess = fetchedAt; + } + return changed; + } + } + + private VersionStatusDto fetch(String serverUrl) { + try { + VersionStatusDto version = serverApiService.serverVersion(serverUrl); + return version == null ? SERVER_UNAVAILABLE : version; + } catch (RuntimeException e) { + LOGGER.debug("Version of {} is unavailable: {}", serverUrl, e.getMessage()); + return SERVER_UNAVAILABLE; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3a82616..aaa3289 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,6 +2,10 @@ server: port: ${CLIENT_PORT:8081} spring: + task: + scheduling: + pool: + size: 2 web: resources: cache: @@ -14,3 +18,7 @@ mediagarrd: pickup-interval: ${CLIENT_PICKUP_INTERVAL:PT12H} server-port: ${MEDIAGARRD_SERVER_PORT:38471} preferred-server-ip: ${MEDIAGARRD_SERVER_IP:} + update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Client} + github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} + update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} + backup-run-timeout: ${CLIENT_BACKUP_RUN_TIMEOUT:PT6H} diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css index b749ca2..f9d15f6 100644 --- a/src/main/resources/static/css/mediagarrd.css +++ b/src/main/resources/static/css/mediagarrd.css @@ -197,6 +197,28 @@ button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } .stat-key { color: var(--muted); font-size: 0.75rem; letter-spacing: 0.03em; } .stat-val { font-weight: 600; text-align: right; font-variant-numeric: tabular-nums; } +.version-list { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; padding: 1rem; } +@media (max-width: 900px) { .version-list { grid-template-columns: 1fr; } } +.version-row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.3rem 0.75rem; + padding: 0.7rem 0.9rem; + background: var(--surface-raised); + border: 1px solid var(--border); + font-size: 0.83rem; +} +.version-name { min-width: 3.5rem; color: var(--muted); font-size: 0.75rem; letter-spacing: 0.03em; } +.version-number { font-family: var(--mono); font-weight: 600; font-variant-numeric: tabular-nums; } +.version-state { margin-left: auto; text-align: right; font-weight: 600; } +.version-row.current .version-state { color: #a3e8bc; } +.version-row.unknown .version-state, +.version-row.checking .version-state { color: var(--muted); font-weight: 400; } +.version-row.outdated { background: #1c0606; border-color: #3b1111; color: #fca5a5; } +.version-row.outdated .version-name { color: #fca5a5; } +.release-link { flex-basis: 100%; color: inherit; font-size: 0.78rem; text-decoration: underline; text-underline-offset: 2px; } + .tag { display: inline-block; padding: 0.12rem 0.45rem; diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 73c4516..621da1e 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -19,7 +19,7 @@
- Connecting... + Connecting…
@@ -61,7 +61,7 @@
Server Status
-

No server connected.

+

Connecting…

+
@@ -132,6 +133,24 @@ + +
+
Versions
+
+
+ Server + — + Checking… + +
+
+ Client + — + Checking… + +
+
+
diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js index 7e636d3..83933a1 100644 --- a/src/main/resources/static/js/api.js +++ b/src/main/resources/static/js/api.js @@ -17,7 +17,7 @@ const encode = encodeURIComponent; export const api = { status: () => request('GET', '/api/client/status'), discover: () => request('POST', '/api/client/discover'), - serverHealth: () => request('GET', '/api/client/server-health'), + dashboard: () => request('GET', '/api/client/dashboard'), selectServer: (selection) => request('PUT', '/api/client/server', selection), listBackups: () => request('GET', '/api/client/backups'), runBackup: () => request('POST', '/api/client/backups/run'), diff --git a/src/main/resources/static/js/backups.js b/src/main/resources/static/js/backups.js index 4d9aba4..19eee41 100644 --- a/src/main/resources/static/js/backups.js +++ b/src/main/resources/static/js/backups.js @@ -3,7 +3,7 @@ import { bytes, percent, relativeTime } from './format.js'; const POLL_INTERVAL_MS = 350; -export function initBackups({ root, actions }, notify, { refreshHealth }) { +export function initBackups({ root, actions }, notify) { const rows = root.querySelector('tbody'); const empty = root.querySelector('[data-empty]'); const headers = root.querySelectorAll('th[data-sort-key]'); @@ -18,6 +18,7 @@ export function initBackups({ root, actions }, notify, { refreshHealth }) { let runInFlight = false; let latestTask = null; let pollTimer = null; + let latestRequest = 0; function renderActions() { const backupBusy = serverRunning || runInFlight; @@ -82,10 +83,14 @@ export function initBackups({ root, actions }, notify, { refreshHealth }) { } async function refresh() { + const request = ++latestRequest; try { - backups = await api.listBackups() || []; + const loaded = await api.listBackups() || []; + if (request !== latestRequest) return; + backups = loaded; renderTable(); } catch (error) { + if (request !== latestRequest) return; backups = []; renderTable(`${error.message}. Connect to a server to view archives.`); } @@ -166,12 +171,11 @@ export function initBackups({ root, actions }, notify, { refreshHealth }) { renderActions(); try { await api.runBackup(); - await refresh(); } catch (error) { notify.error(error); } finally { runInFlight = false; - await refreshHealth(); + renderActions(); } }); @@ -196,11 +200,15 @@ export function initBackups({ root, actions }, notify, { refreshHealth }) { return { refresh, + rerender: () => renderTable(), + clear() { + latestRequest++; + backups = []; + renderTable('No backups loaded. Connect to a server to view archives.'); + }, setServerRunning(running) { - const finished = serverRunning && !running; serverRunning = running; renderActions(); - if (finished) refresh(); }, }; } diff --git a/src/main/resources/static/js/connection.js b/src/main/resources/static/js/connection.js index a081ce6..47a8896 100644 --- a/src/main/resources/static/js/connection.js +++ b/src/main/resources/static/js/connection.js @@ -1,7 +1,7 @@ import { api } from './api.js'; -import { formatInterval } from './format.js'; +import { linkView, planKnown } from './view-model.js'; -export function initConnection({ root, statusPanel, badge }, notify, { onServerChanged, onHealth, onStatus }) { +export function initConnection({ root, statusPanel, badge }, notify, { resync }) { const ipForm = root.querySelector('[data-ip-form]'); const known = root.querySelector('[data-known]'); const controls = root.querySelectorAll('button, input, select'); @@ -9,59 +9,53 @@ export function initConnection({ root, statusPanel, badge }, notify, { onServerC const scanNote = root.querySelector('[data-scan-note]'); const details = statusPanel.querySelector('[data-details]'); const noServer = statusPanel.querySelector('[data-no-server]'); - const state = statusPanel.querySelector('[data-state]'); + const degraded = statusPanel.querySelector('[data-degraded]'); + const runState = statusPanel.querySelector('[data-state]'); let busy = false; - let connected = null; - let healthRequest = null; + let latest = null; + let renderedFor; + let deferred = false; function setBadge(kind, label) { badge.className = `conn-badge ${kind}`; badge.querySelector('[data-label]').textContent = label; } - function renderHealth(health) { - details.hidden = !health.connected; - noServer.hidden = health.connected; - if (!health.connected) { - noServer.textContent = health.activeServer ? `${health.activeServer} is not responding.` : 'No server connected.'; - if (!busy) setBadge(health.activeServer ? 'down' : '', health.activeServer ? 'Unreachable' : 'Not Connected'); - return; - } - const server = health.serverStatus; - statusPanel.querySelector('[data-url]').textContent = health.activeServer; - statusPanel.querySelector('[data-interval]').textContent = server ? formatInterval(server.backupInterval) : '—'; - statusPanel.querySelector('[data-retention]').textContent = server ? `${server.backupRetentionCount} archives` : '—'; - state.textContent = server?.running ? 'Running' : 'Idle'; - state.classList.toggle('running', Boolean(server?.running)); - if (!busy) setBadge('ok', health.activeServer.replace(/^https?:\/\//, '')); + function renderKnown(state) { + const plan = planKnown({ + shown: [...known.options].map((option) => option.value), + knownServers: state.knownServers, + activeServer: state.activeServer, + selected: known.value, + focused: document.activeElement === known, + switched: renderedFor !== undefined && renderedFor !== state.activeServer, + }); + deferred = plan.action === 'defer'; + if (plan.action === 'defer') return; + renderedFor = state.activeServer; + if (plan.action === 'keep') return; + const options = plan.values[0] === '' + ? [new Option('— none discovered yet —', '')] + : plan.values.map((server) => new Option(server, server, false, server === plan.selected)); + known.replaceChildren(...options); } - function refreshHealth() { - healthRequest ??= api.serverHealth() - .catch(() => ({ connected: false })) - .then((health) => { - const reconnected = health.connected && connected === false; - connected = health.connected; - renderHealth(health); - onHealth(health); - if (reconnected) onServerChanged(); - }) - .finally(() => { healthRequest = null; }); - return healthRequest; - } - - function renderKnown(status) { - const servers = status.knownServers || []; - const options = servers.map((server) => new Option(server, server, false, server === status.activeServer)); - known.replaceChildren(...(options.length ? options : [new Option('— none discovered yet —', '')])); - } - - async function refreshStatus() { - const status = await api.status(); - renderKnown(status); - onStatus(status); - await healthRequest; - await refreshHealth(); + function render(state) { + latest = state; + const view = linkView(state); + details.hidden = !view.showDetails; + noServer.hidden = view.showDetails; + noServer.textContent = view.message; + degraded.hidden = !view.degraded; + if (view.showDetails) { + statusPanel.querySelector('[data-url]').textContent = view.url; + statusPanel.querySelector('[data-interval]').textContent = view.interval; + statusPanel.querySelector('[data-retention]').textContent = view.retention; + runState.textContent = view.running ? 'Running' : 'Idle'; + runState.classList.toggle('running', view.running); + } + if (!busy) setBadge(view.badge.kind, view.badge.label); + if (state.loaded) renderKnown(state); } async function connect(label, action) { @@ -80,9 +74,8 @@ export function initConnection({ root, statusPanel, badge }, notify, { onServerC busy = false; scanBar.classList.remove('active'); controls.forEach((control) => { control.disabled = false; }); - connected = null; - await refreshStatus().catch(notify.error); - if (result) onServerChanged(); + if (latest) render(latest); + await resync(); return result; } @@ -111,5 +104,9 @@ export function initConnection({ root, statusPanel, badge }, notify, { onServerC scanNote.textContent = found ? `Last scan: found ${count} server${count === 1 ? '' : 's'}.` : 'Last scan: failed.'; }); - return { refreshStatus, refreshHealth }; + known.addEventListener('blur', () => { + if (deferred && latest) renderKnown(latest); + }); + + return { render }; } diff --git a/src/main/resources/static/js/dashboard-model.js b/src/main/resources/static/js/dashboard-model.js new file mode 100644 index 0000000..15fbf25 --- /dev/null +++ b/src/main/resources/static/js/dashboard-model.js @@ -0,0 +1,87 @@ +function reachableLink(link) { + return link === 'LIVE' || link === 'DEGRADED'; +} + +export function canLoadBackups(state) { + return state.loaded && state.clientReachable && state.activeServer !== null && reachableLink(state.link); +} + +export function emptyState() { + return { + loaded: false, + clientReachable: true, + activeServer: null, + knownServers: [], + link: 'DOWN', + running: null, + health: null, + versions: null, + }; +} + +function fromSnapshot(payload) { + return { + loaded: true, + clientReachable: true, + activeServer: payload.activeServer || null, + knownServers: payload.knownServers || [], + link: payload.link || 'DOWN', + running: payload.running ?? null, + health: payload.health || null, + versions: payload.versions || null, + }; +} + +export function reduce(state, name, payload) { + if (name === 'client') { + const reachable = Boolean(payload?.reachable); + return reachable === state.clientReachable ? state : { ...state, clientReachable: reachable }; + } + if (name === 'snapshot') return fromSnapshot(payload || {}); + const base = state.clientReachable ? state : { ...state, clientReachable: true }; + if (!state.loaded) return base; + switch (name) { + case 'link': { + const link = payload.state || 'DOWN'; + return { ...base, link, running: reachableLink(link) ? base.running : null }; + } + case 'state': + return { ...base, running: Boolean(payload.running) }; + case 'run-started': + return { ...base, running: true }; + case 'run-finished': + return { ...base, running: false }; + case 'servers': + return { ...base, knownServers: payload.knownServers || [], activeServer: payload.activeServer || null }; + case 'config': + return { ...base, health: { backupInterval: payload.backupInterval, backupRetentionCount: payload.backupRetentionCount } }; + case 'versions': + return { ...base, versions: payload }; + default: + return base; + } +} + +export function changes(prev, next, eventName) { + const none = { serverChanged: false, clearBackups: false, refreshBackups: false }; + if (!next.loaded) return none; + const first = !prev.loaded; + const serverChanged = !first && prev.activeServer !== next.activeServer; + const up = canLoadBackups(next); + const reachedAgain = !first && ( + (!reachableLink(prev.link) && reachableLink(next.link)) + || (!prev.clientReachable && next.clientReachable) + ); + const finished = prev.running === true && next.running === false; + const announced = eventName === 'backups-changed' || eventName === 'run-finished'; + return { + serverChanged, + clearBackups: serverChanged, + refreshBackups: up && (first || serverChanged || reachedAgain || finished || announced), + }; +} + +export function applyEvent(state, name, payload) { + const next = reduce(state, name, payload); + return { state: next, effects: changes(state, next, name) }; +} diff --git a/src/main/resources/static/js/events.js b/src/main/resources/static/js/events.js new file mode 100644 index 0000000..566bccf --- /dev/null +++ b/src/main/resources/static/js/events.js @@ -0,0 +1,91 @@ +import { createReachability } from './reachability.js'; + +const EVENTS_URL = '/api/client/events'; +const EVENT_NAMES = ['snapshot', 'link', 'state', 'run-started', 'run-finished', 'servers', 'config', 'backups-changed', 'versions', 'ping']; +const RETRY_MIN_MS = 2000; +const RETRY_MAX_MS = 30000; +const SILENCE_LIMIT_MS = 60000; +const SILENCE_CHECK_MS = 15000; +const RECONNECT_GRACE_MS = 8000; + +export function initEvents({ onEvent, onConnection }) { + let source = null; + let retryTimer = null; + let retryDelay = RETRY_MIN_MS; + let lastMessageAt = 0; + const reachability = createReachability({ graceMs: RECONNECT_GRACE_MS, onChange: onConnection }); + + function parse(event) { + try { + return JSON.parse(event.data); + } catch { + return null; + } + } + + function scheduleReopen() { + if (retryTimer) return; + retryTimer = setTimeout(() => { + retryTimer = null; + open(); + }, retryDelay); + retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS); + } + + function close() { + reachability.cancel(); + clearTimeout(retryTimer); + retryTimer = null; + if (source) source.close(); + source = null; + } + + function open() { + if (source || document.hidden) return; + const created = new EventSource(EVENTS_URL); + source = created; + lastMessageAt = Date.now(); + created.addEventListener('open', () => { + lastMessageAt = Date.now(); + retryDelay = RETRY_MIN_MS; + reachability.alive(); + }); + created.addEventListener('error', () => { + if (source !== created) return; + const closed = created.readyState === EventSource.CLOSED; + reachability.failed(closed); + if (!closed) return; + close(); + scheduleReopen(); + }); + EVENT_NAMES.forEach((name) => created.addEventListener(name, (event) => { + lastMessageAt = Date.now(); + reachability.alive(); + const payload = parse(event); + if (payload && name !== 'ping') onEvent(name, payload); + })); + } + + document.addEventListener('visibilitychange', () => { + if (document.hidden) close(); + else open(); + }); + + window.addEventListener('pageshow', (event) => { + if (event.persisted && (!source || source.readyState === EventSource.CLOSED)) { + close(); + open(); + } + }); + + setInterval(() => { + if (source && Date.now() - lastMessageAt > SILENCE_LIMIT_MS) { + close(); + open(); + } + }, SILENCE_CHECK_MS); + + open(); + + return { open, close }; +} diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js index aaaa268..6925e08 100644 --- a/src/main/resources/static/js/main.js +++ b/src/main/resources/static/js/main.js @@ -1,31 +1,81 @@ import { initBackups } from './backups.js'; import { initConnection } from './connection.js'; +import { applyEvent, canLoadBackups, emptyState } from './dashboard-model.js'; +import { initEvents } from './events.js'; +import { api } from './api.js'; import { createNotifier } from './notify.js'; import { initPickupInterval } from './pickup-interval.js'; import { initServerConfig } from './server-config.js'; import { initViews } from './views.js'; +import { initVersions } from './versions.js'; -const HEALTH_INTERVAL_MS = 7000; +const DASHBOARD_REFRESH_MS = 60000; const notify = createNotifier(document.getElementById('banner')); const pickupInterval = initPickupInterval(document.getElementById('pickupIntervalForm'), notify); const serverConfig = initServerConfig(document.querySelector('[data-view="config"]'), notify); +const versions = initVersions(document.getElementById('versions')); const backups = initBackups({ root: document.getElementById('backups'), actions: document.getElementById('actions'), -}, notify, { refreshHealth: () => connection.refreshHealth() }); - +}, notify); const connection = initConnection({ root: document.getElementById('connection'), statusPanel: document.getElementById('serverStatus'), badge: document.getElementById('connBadge'), -}, notify, { - onServerChanged: () => { - backups.refresh(); - serverConfig.serverChanged(); +}, notify, { resync: () => resync() }); + +let state = emptyState(); +let pushes = 0; +let pickupLoad = 'idle'; + +function loadPickupInterval() { + if (pickupLoad !== 'idle') return; + pickupLoad = 'loading'; + api.status() + .then((status) => { + pickupInterval.show(status.pickupInterval); + pickupLoad = 'done'; + }) + .catch(() => { pickupLoad = 'idle'; }); +} + +function dispatch(name, payload) { + const { state: next, effects } = applyEvent(state, name, payload); + const unchanged = next === state; + if (unchanged && !effects.refreshBackups) return; + state = next; + if (!unchanged) { + connection.render(state); + backups.setServerRunning(state.running === true); + if (state.loaded) versions.render(state.versions); + } + if (effects.clearBackups) backups.clear(); + if (effects.serverChanged) serverConfig.serverChanged(); + if (effects.refreshBackups) backups.refresh(); + if (state.loaded && state.clientReachable) loadPickupInterval(); +} + +async function resync() { + const startedAt = pushes; + try { + const snapshot = await api.dashboard(); + if (pushes === startedAt) dispatch('snapshot', snapshot); + } catch (error) { + if (error instanceof TypeError && pushes === startedAt) dispatch('client', { reachable: false }); + } +} + +function refreshBackupsIfUp() { + if (canLoadBackups(state)) backups.refresh(); +} + +initEvents({ + onEvent: (name, payload) => { + pushes++; + dispatch(name, payload); }, - onHealth: (health) => backups.setServerRunning(Boolean(health.serverStatus?.running)), - onStatus: (status) => pickupInterval.show(status.pickupInterval), + onConnection: (reachable) => dispatch('client', { reachable }), }); document.addEventListener('click', (event) => { @@ -35,16 +85,29 @@ document.addEventListener('click', (event) => { setTimeout(() => button.classList.remove('clicked'), 140); }); +let viewShown = false; initViews((view) => { notify.clear(); if (view === 'config') serverConfig.load(); - else connection.refreshHealth(); + else if (viewShown) { + resync(); + refreshBackupsIfUp(); + } + viewShown = true; }); -connection.refreshStatus().catch(notify.error).then(backups.refresh); +loadPickupInterval(); +resync(); + setInterval(() => { - if (!document.hidden) connection.refreshHealth(); -}, HEALTH_INTERVAL_MS); + if (document.hidden) return; + resync(); + if (location.hash === '#config') return; + backups.rerender(); +}, DASHBOARD_REFRESH_MS); + document.addEventListener('visibilitychange', () => { - if (!document.hidden) connection.refreshHealth(); + if (document.hidden) return; + resync(); + if (location.hash !== '#config') refreshBackupsIfUp(); }); diff --git a/src/main/resources/static/js/pickup-interval.js b/src/main/resources/static/js/pickup-interval.js index c071e5b..342980b 100644 --- a/src/main/resources/static/js/pickup-interval.js +++ b/src/main/resources/static/js/pickup-interval.js @@ -3,12 +3,16 @@ import { seconds, toDuration } from './format.js'; export function initPickupInterval(form, notify) { const minutes = form.elements.minutes; + let edited = false; + + minutes.addEventListener('input', () => { edited = true; }); form.addEventListener('submit', async (event) => { event.preventDefault(); notify.clear(); try { const status = await api.updatePickupInterval(toDuration(Number(minutes.value))); + edited = false; show(status.pickupInterval); notify.ok('Pickup interval saved'); } catch (error) { @@ -17,6 +21,7 @@ export function initPickupInterval(form, notify) { }); function show(interval) { + if (edited) return; const value = Math.round(seconds(interval) / 60); if (value) minutes.value = value; } diff --git a/src/main/resources/static/js/reachability.js b/src/main/resources/static/js/reachability.js new file mode 100644 index 0000000..ad6a55e --- /dev/null +++ b/src/main/resources/static/js/reachability.js @@ -0,0 +1,29 @@ +export function createReachability({ graceMs, onChange, setTimer = setTimeout, clearTimer = clearTimeout }) { + let timer = null; + + function cancel() { + if (timer === null) return; + clearTimer(timer); + timer = null; + } + + return { + cancel, + failed(closed) { + if (closed) { + cancel(); + onChange(false); + return; + } + if (timer !== null) return; + timer = setTimer(() => { + timer = null; + onChange(false); + }, graceMs); + }, + alive() { + cancel(); + onChange(true); + }, + }; +} diff --git a/src/main/resources/static/js/versions.js b/src/main/resources/static/js/versions.js new file mode 100644 index 0000000..202fc32 --- /dev/null +++ b/src/main/resources/static/js/versions.js @@ -0,0 +1,27 @@ +import { versionsView } from './view-model.js'; + +export function initVersions(root) { + const rows = { + server: root.querySelector('[data-row="server"]'), + client: root.querySelector('[data-row="client"]'), + }; + + function renderRow(row, view) { + const link = row.querySelector('[data-link]'); + row.classList.remove('current', 'outdated', 'unknown', 'checking'); + row.classList.add(view.kind); + row.querySelector('[data-version]').textContent = view.version; + row.querySelector('[data-state]').textContent = view.label; + link.hidden = !view.href; + if (view.href) link.href = view.href; + else link.removeAttribute('href'); + } + + return { + render(versions) { + const view = versionsView(versions); + renderRow(rows.server, view.server); + renderRow(rows.client, view.client); + }, + }; +} diff --git a/src/main/resources/static/js/view-model.js b/src/main/resources/static/js/view-model.js new file mode 100644 index 0000000..6f385ab --- /dev/null +++ b/src/main/resources/static/js/view-model.js @@ -0,0 +1,74 @@ +import { formatInterval } from './format.js'; + +const RELEASE_URL = /^https?:\/\//; + +export function linkView(state) { + const none = { showDetails: false, url: '', interval: '—', retention: '—', running: false, degraded: false }; + if (!state.clientReachable) { + return { ...none, badge: { kind: 'down', label: 'Client unreachable' }, message: 'Client unreachable. Retrying…' }; + } + if (!state.loaded) { + return { ...none, badge: { kind: 'checking', label: 'Connecting…' }, message: 'Connecting…' }; + } + if (!state.activeServer) { + return { ...none, badge: { kind: '', label: 'Not Connected' }, message: 'No server connected.' }; + } + if (state.link === 'CONNECTING') { + return { ...none, badge: { kind: 'checking', label: 'Connecting…' }, message: `Connecting to ${state.activeServer}…` }; + } + if (state.link === 'DOWN') { + return { ...none, badge: { kind: 'down', label: 'Unreachable' }, message: `${state.activeServer} is not responding.` }; + } + return { + badge: { kind: 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, + message: '', + showDetails: true, + url: state.activeServer, + interval: state.health ? formatInterval(state.health.backupInterval) : '—', + retention: state.health ? `${state.health.backupRetentionCount} archives` : '—', + running: state.running === true, + degraded: state.link === 'DEGRADED', + }; +} + +export function planKnown({ shown, knownServers, activeServer, selected, focused, switched }) { + const values = knownServers.length ? knownServers : ['']; + if (!switched) { + const unchanged = values.length === shown.length && values.every((value, index) => shown[index] === value); + if (unchanged) return { action: 'keep' }; + if (focused) return { action: 'defer' }; + } + const keep = !switched && knownServers.includes(selected); + return { action: 'render', values, selected: keep ? selected : activeServer }; +} + +export function classifyVersion(status) { + if (status?.updateAvailable) return 'outdated'; + if (status?.checkState === 'NOT_CHECKED') return 'checking'; + if (status?.checkState === 'OK' || status?.checkState === 'NO_RELEASES') return 'current'; + return 'unknown'; +} + +export function versionRowView(status, missingText) { + const kind = classifyVersion(status); + const label = { + current: 'Up-to-date', + outdated: `Update available: v${status?.latestVersion}`, + checking: 'Checking…', + unknown: status ? 'Unable to check' : missingText, + }[kind]; + const showLink = kind === 'outdated' && RELEASE_URL.test(status.releaseUrl || ''); + return { + kind, + label, + version: status?.currentVersion ? `v${status.currentVersion}` : '—', + href: showLink ? status.releaseUrl : null, + }; +} + +export function versionsView(versions) { + return { + server: versionRowView(versions?.server, versions ? 'No server connected' : 'Unable to check'), + client: versionRowView(versions?.client, 'Unable to check'), + }; +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java index 2a6aa76..4080d24 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java @@ -1,12 +1,15 @@ package wellatleastitried.mediagarrdclient; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.file.Path; +import java.time.Duration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -27,11 +30,20 @@ class MediaGarrdTest { @Autowired MockMvc mockMvc; + @Autowired + Configuration configuration; + @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + registry.add("mediagarrd.client.github-api-base-url", () -> "http://127.0.0.1:1"); + } + + @Test + void bindsTheBackupRunTimeoutDefault() { + assertEquals(Duration.ofHours(6), configuration.getBackupRunTimeout()); } @Test @@ -49,4 +61,14 @@ void reportsStatusWithoutAServer() throws Exception { .andExpect(status().isOk()) .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); } + + @Test + void reportsTheDashboardWithTheClientVersionAndNoServer() throws Exception { + mockMvc.perform(get("/api/client/dashboard")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.link").value("DOWN")) + .andExpect(jsonPath("$.activeServer").doesNotExist()) + .andExpect(jsonPath("$.versions.client.checkState").exists()) + .andExpect(jsonPath("$.versions.server").doesNotExist()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java index b59d047..2106231 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -1,8 +1,10 @@ package wellatleastitried.mediagarrdclient.api; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -25,9 +27,15 @@ import org.springframework.web.server.ResponseStatusException; import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; import wellatleastitried.mediagarrdclient.service.BackupPickupService; import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; import wellatleastitried.mediagarrdclient.service.ServerApiService; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; @@ -49,6 +57,20 @@ class ClientControllerTest { @MockBean BackupPickupService backupPickupService; + @MockBean + DashboardService dashboardService; + + @Test + void mapsABackupRunTimeoutToAGatewayTimeoutWithAnErrorBody() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + doThrow(new BackupRunTimeoutException("The backup is probably still running on the server.", null)) + .when(serverApiService).triggerBackup("http://server:8080"); + + mockMvc.perform(post("/api/client/backups/run")) + .andExpect(status().isGatewayTimeout()) + .andExpect(jsonPath("$.error").value("The backup is probably still running on the server.")); + } + @Test void statusEndpointReturnsState() throws Exception { when(stateService.getActiveServer()).thenReturn("http://server:8080"); @@ -106,10 +128,32 @@ void pickupEndpointStartsTask() throws Exception { } @Test - void statusConnectsThePreferredServerFirst() throws Exception { + void statusHasNoNetworkSideEffect() throws Exception { mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); - verify(discoveryService).connectPreferredServer(); + verifyNoInteractions(discoveryService, serverApiService); + } + + @Test + void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws Exception { + when(dashboardService.state()).thenReturn(new DashboardState( + "http://server:8080", + List.of("http://server:8080"), + LinkState.DEGRADED, + true, + new HealthSummary(Duration.ofHours(6), 5), + new VersionsDto(null, null))); + + mockMvc.perform(get("/api/client/dashboard")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.activeServer").value("http://server:8080")) + .andExpect(jsonPath("$.knownServers[0]").value("http://server:8080")) + .andExpect(jsonPath("$.link").value("DEGRADED")) + .andExpect(jsonPath("$.running").value(true)) + .andExpect(jsonPath("$.health.backupRetentionCount").value(5)) + .andExpect(jsonPath("$.versions.server").doesNotExist()); + + verifyNoInteractions(serverApiService, discoveryService); } @Test diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java new file mode 100644 index 0000000..f19e41e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java @@ -0,0 +1,74 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdclient.service.DashboardService; + +@WebMvcTest(controllers = ClientEventsController.class) +@Timeout(20) +class ClientEventsControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + DashboardService dashboard; + + @Test + void opensAnUnbufferedEventStream() throws Exception { + SseEmitter emitter = new SseEmitter(60_000L); + emitter.send(SseEmitter.event().name("link").data("{}")); + when(dashboard.subscribe()).thenReturn(Optional.of(emitter)); + + mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", "no-cache")) + .andExpect(header().string("X-Accel-Buffering", "no")) + .andExpect(content().string("event:link\ndata:{}\n\n")); + + emitter.complete(); + } + + @Test + void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { + when(dashboard.subscribe()).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isServiceUnavailable()) + .andExpect(content().string("")); + } + + @Test + void aBrowserThatWentAwayEndsTheStreamWithoutAnError() throws Exception { + SseEmitter emitter = new SseEmitter(60_000L); + emitter.send(SseEmitter.event().name("link").data("{}")); + when(dashboard.subscribe()).thenReturn(Optional.of(emitter)); + MvcResult started = mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andReturn(); + + emitter.completeWithError(new IOException("Broken pipe")); + + mockMvc.perform(asyncDispatch(started)).andExpect(status().isOk()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java new file mode 100644 index 0000000..c511d84 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java @@ -0,0 +1,262 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.function.LongFunction; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +@Timeout(30) +class ClientEventBroadcasterTest { + + private static final Duration LONG_PING = Duration.ofMinutes(10); + + static class RecordingEmitter extends SseEmitter { + + final BlockingQueue sent = new LinkedBlockingQueue<>(); + final CountDownLatch completed = new CountDownLatch(1); + + RecordingEmitter(Long timeout) { + super(timeout); + } + + @Override + public void send(SseEventBuilder builder) throws IOException { + StringBuilder text = new StringBuilder(); + for (ResponseBodyEmitter.DataWithMediaType part : builder.build()) { + text.append(part.getData()); + } + sent.add(text.toString()); + } + + @Override + public void complete() { + completed.countDown(); + super.complete(); + } + + String next() throws InterruptedException { + String event = sent.poll(5, TimeUnit.SECONDS); + assertNotNull(event, "timed out waiting for an event"); + return event; + } + + String nextContaining(String marker) throws InterruptedException { + while (true) { + String event = next(); + if (event.contains(marker)) { + return event; + } + } + } + } + + static class FailingEmitter extends RecordingEmitter { + + FailingEmitter(Long timeout) { + super(timeout); + } + + @Override + public void send(SseEventBuilder builder) throws IOException { + throw new IOException("client went away"); + } + } + + static class StuckEmitter extends RecordingEmitter { + + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + + StuckEmitter(Long timeout) { + super(timeout); + } + + @Override + public synchronized void send(SseEventBuilder builder) throws IOException { + entered.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + private final List writers = new CopyOnWriteArrayList<>(); + private final ThreadFactory threadFactory = runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + writers.add(thread); + return thread; + }; + private final List broadcasters = new ArrayList<>(); + + @AfterEach + void tearDown() throws InterruptedException { + broadcasters.forEach(ClientEventBroadcaster::shutdown); + for (Thread writer : writers) { + writer.join(5000); + } + } + + private ClientEventBroadcaster broadcaster(Duration ping, int max, int queue, LongFunction factory) { + return broadcaster(ping, max, queue, Duration.ofMinutes(10), factory); + } + + private ClientEventBroadcaster broadcaster(Duration ping, int max, int queue, Duration lifetime, LongFunction factory) { + ClientEventBroadcaster broadcaster = new ClientEventBroadcaster(ping, max, queue, lifetime, Duration.ofMinutes(5), threadFactory, factory); + broadcasters.add(broadcaster); + return broadcaster; + } + + private ClientEventBroadcaster broadcaster() { + return broadcaster(LONG_PING, 32, 64, RecordingEmitter::new); + } + + private static final List SNAPSHOT = List.of(new ClientEvent("snapshot", "{\"link\":\"DOWN\"}")); + + private static RecordingEmitter subscribe(ClientEventBroadcaster broadcaster) { + return (RecordingEmitter) broadcaster.subscribe(SNAPSHOT).orElseThrow(); + } + + @Test + void sendsTheInitialEventsFirstAndTellsTheBrowserHowLongToWaitBeforeReconnecting() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + + RecordingEmitter emitter = subscribe(broadcaster); + + assertEquals("retry:5000\nevent:snapshot\ndata:{\"link\":\"DOWN\"}\n\n", emitter.next()); + assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + } + + @Test + void theReconnectHintIsSentOnlyOnce() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter emitter = subscribe(broadcaster); + emitter.next(); + + broadcaster.publish("run-started", "{\"running\":true}"); + + assertEquals("event:run-started\ndata:{\"running\":true}\n\n", emitter.next()); + } + + @Test + void publishesAreOrderedAfterTheInitialEventsForALateSubscriber() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + broadcaster.publish("link", "{\"state\":\"LIVE\"}"); + RecordingEmitter emitter = subscribe(broadcaster); + broadcaster.publish("state", "{\"running\":true}"); + + assertTrue(emitter.next().contains("event:snapshot")); + assertTrue(emitter.next().contains("event:state")); + assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + } + + @Test + void fansEventsOutToEverySubscriberInOrder() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter first = subscribe(broadcaster); + RecordingEmitter second = subscribe(broadcaster); + first.next(); + second.next(); + + broadcaster.publish("run-started", "{\"running\":true}"); + broadcaster.publish("run-finished", "{\"running\":false,\"status\":\"FAILED\"}"); + + for (RecordingEmitter emitter : List.of(first, second)) { + assertEquals("event:run-started\ndata:{\"running\":true}\n\n", emitter.next()); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"FAILED\"}\n\n", emitter.next()); + } + } + + @Test + void sendsNamedPingsWhenIdle() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(Duration.ofMillis(20), 32, 64, RecordingEmitter::new); + RecordingEmitter emitter = subscribe(broadcaster); + + emitter.nextContaining("event:ping\ndata:{}\n\n"); + } + + @Test + void rejectsSubscribersBeyondTheCap() { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 2, 64, RecordingEmitter::new); + subscribe(broadcaster); + subscribe(broadcaster); + + assertTrue(broadcaster.subscribe(SNAPSHOT).isEmpty()); + assertEquals(2, broadcaster.subscriberCount()); + } + + @Test + void forgetsASubscriberWhoseWriteFailsAndFreesItsSlot() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 1, 64, FailingEmitter::new); + + broadcaster.subscribe(SNAPSHOT); + writers.get(0).join(5000); + + assertEquals(0, broadcaster.subscriberCount()); + assertTrue(broadcaster.subscribe(SNAPSHOT).isPresent()); + } + + @Test + void shutdownCompletesEverySubscriber() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter emitter = subscribe(broadcaster); + emitter.next(); + + broadcaster.shutdown(); + + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + assertTrue(broadcaster.subscribe(SNAPSHOT).isEmpty()); + } + + @Test + void publishingNeverBlocksOnAStuckSubscriberAndOnlyItsWriterCompletesIt() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 4, 1, StuckEmitter::new); + StuckEmitter stuck = (StuckEmitter) broadcaster.subscribe(SNAPSHOT).orElseThrow(); + assertTrue(stuck.entered.await(5, TimeUnit.SECONDS)); + + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> { + for (int i = 0; i < 5; i++) { + broadcaster.publish("run-started", "{\"running\":true}"); + } + broadcaster.publish("link", "{}"); + }); + + assertEquals(0, broadcaster.subscriberCount()); + assertFalse(stuck.completed.await(200, TimeUnit.MILLISECONDS)); + stuck.release.countDown(); + assertTrue(stuck.completed.await(5, TimeUnit.SECONDS)); + } + + @Test + void theWriterEndsAStreamItselfOnceItsLifetimeIsUp() throws Exception { + ClientEventBroadcaster broadcaster = broadcaster(LONG_PING, 4, 64, Duration.ofMillis(100), RecordingEmitter::new); + + RecordingEmitter emitter = subscribe(broadcaster); + + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java index 0fb435d..d0b9362 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -3,15 +3,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.web.server.ResponseStatusException; @@ -48,6 +52,22 @@ void persistsAndLoadsState() { assertEquals(List.of("state.json"), fileNames()); } + @Test + void setsTheActiveServerOnlyWhileNoneIsSelected() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.setActiveServerIfBlank("http://a:8080"); + state.setActiveServerIfBlank("http://b:8080"); + state.setActiveServerIfBlank(" "); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://a:8080"), state.getKnownServers()); + assertEquals(List.of("http://a:8080"), notified); + assertEquals("http://a:8080", new ClientStateService(configuration, MAPPER).getActiveServer()); + } + @Test void keepsTheActiveServerWhenARescanDoesNotFindIt() { ClientStateService state = new ClientStateService(configuration, MAPPER); @@ -100,4 +120,105 @@ private List fileNames() { throw new IllegalStateException(e); } } + + @Test + void notifiesListenersOnlyWhenTheActiveServerChanges() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.setActiveServer("http://a:8080"); + state.setActiveServer("http://a:8080"); + state.updateKnownServers(List.of("http://b:8080")); + state.setActiveServer("http://b:8080"); + state.setActiveServer(""); + + assertEquals(List.of("http://a:8080", "http://b:8080", ""), notified); + } + + @Test + void notifiesListenersWhenARescanPicksTheFirstActiveServer() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(notified::add); + + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + state.updateKnownServers(List.of("http://b:8080")); + + assertEquals(List.of("http://a:8080"), notified); + } + + @Test + @Timeout(10) + void notifiesListenersWithoutHoldingTheStateLock() throws InterruptedException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + AtomicReference seenByOtherThread = new AtomicReference<>(); + state.addActiveServerListener(url -> { + Thread reader = new Thread(() -> seenByOtherThread.set(state.getActiveServer())); + reader.start(); + try { + reader.join(5000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + + state.setActiveServer("http://a:8080"); + + assertEquals("http://a:8080", seenByOtherThread.get()); + } + + @Test + void keepsNotifyingWhenAListenerFails() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addActiveServerListener(url -> { + throw new IllegalStateException("boom"); + }); + state.addActiveServerListener(notified::add); + + state.setActiveServer("http://a:8080"); + + assertTrue(notified.contains("http://a:8080")); + } + + @Test + void notifiesKnownServersListenersOnlyWhenTheListChanges() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + int[] calls = {0}; + state.addKnownServersListener(() -> calls[0]++); + + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + assertEquals(1, calls[0]); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + assertEquals(1, calls[0]); + state.setActiveServer("http://a:8080"); + assertEquals(1, calls[0]); + state.setActiveServer("http://c:8080"); + assertEquals(2, calls[0]); + state.setActiveServer("http://c:8080"); + assertEquals(2, calls[0]); + state.updateKnownServers(List.of("http://d:8080")); + assertEquals(3, calls[0]); + } + + @Test + @Timeout(10) + void notifiesKnownServersListenersWithoutHoldingTheStateLock() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + AtomicReference> seenByOtherThread = new AtomicReference<>(); + state.addKnownServersListener(() -> { + Thread reader = new Thread(() -> seenByOtherThread.set(state.getKnownServers())); + reader.start(); + try { + reader.join(5000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + + state.updateKnownServers(List.of("http://a:8080")); + + assertEquals(List.of("http://a:8080"), seenByOtherThread.get()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java new file mode 100644 index 0000000..9847b27 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java @@ -0,0 +1,783 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.web.client.ResourceAccessException; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.service.ClientEventBroadcasterTest.RecordingEmitter; + +@Timeout(30) +class DashboardServiceTest { + + private static final ObjectMapper MAPPER = JsonMapper.builder() + .findAndAddModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .build(); + private static final Instant START = Instant.parse("2026-11-12T10:00:00Z"); + private static final String A = "http://a:38471"; + private static final String B = "http://b:38471"; + private static final ServerStatusDto IDLE = new ServerStatusDto(true, false, 5, Duration.ofHours(6)); + private static final ServerStatusDto BUSY = new ServerStatusDto(true, true, 5, Duration.ofHours(6)); + private static final VersionStatusDto SERVER_VERSION = new VersionStatusDto("0.1.0", "0.2.0", "https://example.test/r", true, CheckState.OK, START, null); + private static final VersionStatusDto CLIENT_VERSION = new VersionStatusDto("0.1.0", "0.1.0", null, false, CheckState.OK, START, null); + + @TempDir + Path tempDir; + + private final AtomicReference now = new AtomicReference<>(START); + private final Clock clock = new Clock() { + @Override + public ZoneId getZone() { + return ZoneId.of("UTC"); + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + private final Queue queued = new ArrayDeque<>(); + private final List broadcasters = new ArrayList<>(); + private final ServerApiService serverApi = mock(ServerApiService.class); + private final UpdateCheckService updateCheck = mock(UpdateCheckService.class); + private ClientStateService state; + private ClientEventBroadcaster broadcaster; + private DashboardService dashboard; + + @BeforeEach + void setUp() { + Configuration configuration = new Configuration(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + when(updateCheck.status()).thenReturn(CLIENT_VERSION); + when(serverApi.health(anyString())).thenReturn(IDLE); + when(serverApi.serverVersion(anyString())).thenReturn(SERVER_VERSION); + } + + private void create(Executor executor) { + broadcaster = new ClientEventBroadcaster(Duration.ofMinutes(10), 8, 64, Duration.ofMinutes(5), Duration.ofMinutes(6), runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + return thread; + }, RecordingEmitter::new); + broadcasters.add(broadcaster); + dashboard = new DashboardService(state, broadcaster, serverApi, new VersionService(updateCheck, serverApi, clock), updateCheck, MAPPER, executor, clock); + dashboard.start(); + } + + private void create() { + create(Runnable::run); + } + + @AfterEach + void tearDown() { + broadcasters.forEach(ClientEventBroadcaster::shutdown); + } + + private RecordingEmitter subscribe() { + return (RecordingEmitter) dashboard.subscribe().orElseThrow(); + } + + private static List drain(RecordingEmitter emitter) throws InterruptedException { + List events = new ArrayList<>(); + String next; + while ((next = emitter.sent.poll(150, TimeUnit.MILLISECONDS)) != null) { + events.add(next); + } + return events; + } + + private static String nameOf(String event) { + for (String line : event.split("\n")) { + if (line.startsWith("event:")) { + return line.substring("event:".length()); + } + } + return ""; + } + + private static List names(List events) { + return events.stream().map(DashboardServiceTest::nameOf).toList(); + } + + private void advance(Duration duration) { + now.set(now.get().plus(duration)); + } + + @Test + void startsDownWithNothingKnownAndNoServer() { + create(); + + DashboardState result = dashboard.state(); + + assertEquals(null, result.activeServer()); + assertEquals(List.of(), result.knownServers()); + assertEquals(LinkState.DOWN, result.link()); + assertEquals(null, result.running()); + assertEquals(null, result.health()); + assertEquals(null, result.versions().server()); + assertEquals(CLIENT_VERSION, result.versions().client()); + verify(serverApi, never()).health(anyString()); + } + + @Test + void aFirstSubscriberGetsOneFullSnapshotThatReflectsEverythingTheModelHolds() throws Exception { + state.setActiveServer(A); + create(); + + RecordingEmitter browser = subscribe(); + + String snapshot = browser.next(); + assertEquals("snapshot", nameOf(snapshot)); + assertTrue(snapshot.contains("\"activeServer\":\"" + A + "\""), snapshot); + assertTrue(snapshot.contains("\"knownServers\":[\"" + A + "\"]"), snapshot); + assertTrue(snapshot.contains("\"link\":\"DEGRADED\""), snapshot); + assertTrue(snapshot.contains("\"running\":false"), snapshot); + assertTrue(snapshot.contains("\"health\":{\"backupInterval\":\"PT6H\",\"backupRetentionCount\":5}"), snapshot); + assertTrue(snapshot.contains("\"versions\":{\"client\":{"), snapshot); + assertTrue(snapshot.contains("\"latestVersion\":\"0.2.0\""), snapshot); + assertTrue(drain(browser).isEmpty()); + } + + @Test + void aLateSubscriberGetsTheLatestSnapshotFollowedByGranularEvents() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); + + RecordingEmitter browser = subscribe(); + dashboard.runEvent(A, "run-finished", "{\"running\":false,\"status\":\"COMPLETED\"}", false); + + List events = drain(browser); + assertEquals(List.of("snapshot", "run-finished"), names(events)); + assertTrue(events.get(0).contains("\"link\":\"LIVE\"") && events.get(0).contains("\"running\":true"), events.get(0)); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"COMPLETED\"}\n\n", events.get(1)); + } + + @Test + void theLinkIsLiveWhileTheStreamIsUpDegradedWhenOnlyHealthAnswersAndDownOtherwise() throws Exception { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + create(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + + dashboard.streamUp(A); + assertEquals(LinkState.LIVE, dashboard.state().link()); + + dashboard.streamDown(A); + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + dashboard.runEvent(A, "state", "{\"running\":true}", true); + dashboard.streamUp(A); + dashboard.streamDown(A); + DashboardState down = dashboard.state(); + assertEquals(LinkState.DOWN, down.link()); + assertEquals(null, down.running()); + } + + @Test + void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { + state.setActiveServer(A); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + + dashboard.streamUp(A); + dashboard.streamUp(A); + dashboard.streamDown(A); + + List links = drain(browser).stream().filter(event -> nameOf(event).equals("link")).toList(); + assertEquals(3, links.size()); + assertTrue(links.get(0).contains("\"state\":\"LIVE\"") && links.get(0).contains("\"server\":\"" + A + "\"")); + assertTrue(links.get(1).contains("\"state\":\"CONNECTING\"")); + assertTrue(links.get(2).contains("\"state\":\"DEGRADED\"")); + } + + @Test + void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Exception { + state.setActiveServer(A); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(3)); + dashboard.tick(); + verify(serverApi, never()).health(anyString()); + + doReturn(BUSY).when(serverApi).health(A); + advance(Duration.ofSeconds(5)); + dashboard.tick(); + verify(serverApi, times(1)).health(A); + assertEquals(true, dashboard.state().running()); + assertEquals(List.of("state"), names(drain(browser))); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + List events = drain(browser); + assertEquals(List.of("state"), names(events)); + assertTrue(events.get(0).contains("\"running\":false")); + assertEquals(false, dashboard.state().running()); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertTrue(drain(browser).isEmpty()); + } + + @Test + void aFailedPollMakesTheLinkDownAndASuccessfulOneRecoversIt() throws Exception { + state.setActiveServer(A); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + assertEquals(null, dashboard.state().running()); + + doReturn(BUSY).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + assertEquals(true, dashboard.state().running()); + assertEquals(List.of("link", "link", "state"), names(drain(browser))); + } + + @Test + void doesNotPollEverySevenSecondsOnceTheLinkIsLiveButKeepsAOneMinuteCatchAll() { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(30)); + dashboard.tick(); + advance(Duration.ofSeconds(20)); + dashboard.tick(); + verify(serverApi, never()).health(anyString()); + + advance(Duration.ofSeconds(15)); + dashboard.tick(); + verify(serverApi, times(1)).health(A); + } + + @Test + void aLiveLinkIgnoresPollResultsForLinkAndRunningButKeepsTheHealthSummary() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "state", "{\"running\":false}", false); + RecordingEmitter browser = subscribe(); + browser.next(); + + doReturn(new ServerStatusDto(true, true, 9, Duration.ofHours(1))).when(serverApi).health(A); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + + DashboardState result = dashboard.state(); + assertEquals(LinkState.LIVE, result.link()); + assertEquals(false, result.running()); + assertEquals(9, result.health().backupRetentionCount()); + assertEquals(List.of("config"), names(drain(browser))); + } + + @Test + void streamEventsAreForwardedAndKeepRunningInStep() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingEmitter browser = subscribe(); + browser.next(); + + dashboard.runEvent(A, "state", "{\"running\":false,\"at\":\"t\"}", false); + dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); + assertEquals(true, dashboard.state().running()); + dashboard.backupsChanged(A, "{\"at\":\"t2\"}"); + dashboard.runEvent(A, "run-finished", "{\"running\":false,\"status\":\"FAILED\"}", false); + assertEquals(false, dashboard.state().running()); + + List events = drain(browser); + assertEquals(List.of("state", "run-started", "backups-changed", "run-finished"), names(events)); + assertEquals("event:backups-changed\ndata:{\"at\":\"t2\"}\n\n", events.get(2)); + } + + @Test + void aConfigChangedEventRefetchesHealthOnceAndPushesTheSummaryOnlyWhenItChanged() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + dashboard.configChanged(A); + assertTrue(drain(browser).isEmpty()); + verify(serverApi, times(1)).health(A); + + doReturn(new ServerStatusDto(true, false, 7, Duration.ofHours(2))).when(serverApi).health(A); + dashboard.configChanged(A); + + List events = drain(browser); + assertEquals(List.of("config"), names(events)); + assertEquals("event:config\ndata:{\"backupInterval\":\"PT2H\",\"backupRetentionCount\":7}\n\n", events.get(0)); + verify(serverApi, times(2)).health(A); + } + + @Test + void eventsFromAServerThatIsNoLongerActiveAreIgnored() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + state.setActiveServer(B); + dashboard.sync(); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + dashboard.streamUp(A); + dashboard.runEvent(A, "run-started", "{\"running\":true}", true); + dashboard.backupsChanged(A, "{}"); + dashboard.configChanged(A); + dashboard.streamDown(A); + + assertTrue(drain(browser).isEmpty()); + assertEquals(false, dashboard.state().running()); + verify(serverApi, never()).health(anyString()); + } + + @Test + void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + dashboard.runEvent(A, "state", "{\"running\":true}", true); + RecordingEmitter browser = subscribe(); + browser.next(); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + + state.setActiveServer(B); + dashboard.sync(); + + List events = drain(browser); + assertEquals(List.of("snapshot", "link", "versions"), names(events)); + String snapshot = events.get(0); + assertTrue(snapshot.contains("\"activeServer\":\"" + B + "\""), snapshot); + assertTrue(snapshot.contains("\"knownServers\":[\"" + A + "\",\"" + B + "\"]"), snapshot); + assertTrue(snapshot.contains("\"link\":\"CONNECTING\"") && snapshot.contains("\"running\":null") && snapshot.contains("\"health\":null"), snapshot); + assertTrue(snapshot.contains("\"server\":{\"currentVersion\":null") && snapshot.contains("\"checkState\":\"NOT_CHECKED\""), snapshot); + } + + @Test + void aHealthAnswerThatArrivesAfterASwitchIsDiscarded() { + state.setActiveServer(A); + when(serverApi.health(A)).thenAnswer(call -> { + state.setActiveServer(B); + dashboard.sync(); + return BUSY; + }); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + + create(); + + DashboardState result = dashboard.state(); + assertEquals(B, result.activeServer()); + assertEquals(LinkState.DOWN, result.link()); + assertEquals(null, result.running()); + assertEquals(null, result.health()); + verify(serverApi, times(1)).health(A); + verify(serverApi, times(1)).health(B); + } + + @Test + void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + state.setActiveServer(""); + dashboard.sync(); + advance(Duration.ofSeconds(30)); + dashboard.tick(); + + List events = drain(browser); + assertEquals(List.of("snapshot"), names(events)); + assertTrue(events.get(0).contains("\"activeServer\":null") && events.get(0).contains("\"link\":\"DOWN\"")); + verify(serverApi, never()).health(anyString()); + } + + @Test + void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysTheSame() throws Exception { + state.setActiveServer(A); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + + state.updateKnownServers(List.of(A, B)); + + List events = drain(browser); + assertEquals(List.of("servers"), names(events)); + assertEquals("event:servers\ndata:{\"knownServers\":[\"" + A + "\",\"" + B + "\"],\"activeServer\":\"" + A + "\"}\n\n", events.get(0)); + } + + @Test + void aDiscoveryThatPicksTheFirstActiveServerPushesOneSnapshot() throws Exception { + when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + + state.updateKnownServers(List.of(A, B)); + + assertEquals(List.of("snapshot", "link", "versions"), names(drain(browser))); + assertEquals(A, dashboard.state().activeServer()); + } + + @Test + void theServerVersionIsFetchedOnLinkUpAndAServerSwitchNotOnEveryRead() throws Exception { + state.setActiveServer(A); + create(); + verify(serverApi, times(1)).serverVersion(A); + + dashboard.state(); + dashboard.subscribe(); + dashboard.state(); + verify(serverApi, times(1)).serverVersion(A); + + dashboard.streamUp(A); + verify(serverApi, times(1)).serverVersion(A); + + advance(Duration.ofMinutes(6)); + dashboard.streamDown(A); + verify(serverApi, times(2)).serverVersion(A); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); + state.setActiveServer(B); + dashboard.sync(); + verify(serverApi, never()).serverVersion(B); + doReturn(IDLE).when(serverApi).health(B); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).serverVersion(B); + } + + @Test + void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exception { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(59)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + doReturn(new VersionStatusDto("0.2.0", "0.2.0", null, false, CheckState.OK, START, null)).when(serverApi).serverVersion(A); + advance(Duration.ofMinutes(2)); + dashboard.tick(); + + verify(serverApi, times(1)).serverVersion(A); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); + assertEquals(1, events.size()); + assertTrue(events.get(0).contains("\"server\":{\"currentVersion\":\"0.2.0\""), events.get(0)); + } + + @Test + @SuppressWarnings("unchecked") + void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { + state.setActiveServer(A); + create(); + ArgumentCaptor> listener = ArgumentCaptor.forClass(Consumer.class); + verify(updateCheck).addStatusListener(listener.capture()); + RecordingEmitter browser = subscribe(); + browser.next(); + VersionStatusDto updated = new VersionStatusDto("0.1.0", "0.3.0", "https://example.test/c", true, CheckState.OK, START, null); + when(updateCheck.status()).thenReturn(updated); + + listener.getValue().accept(updated); + + List events = drain(browser); + assertEquals(List.of("versions"), names(events)); + assertTrue(events.get(0).contains("\"latestVersion\":\"0.3.0\"") && events.get(0).contains("\"updateAvailable\":true"), events.get(0)); + assertTrue(events.get(0).contains("\"server\":{")); + } + + @Test + void retriesAnUnavailableServerVersionAfterTenMinutes() { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).serverVersion(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(9)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + advance(Duration.ofMinutes(1)); + dashboard.tick(); + verify(serverApi, times(1)).serverVersion(A); + } + + @Test + void healthRequestsThatPileUpWhileOneIsRunningAreCoalesced() { + state.setActiveServer(A); + create(queued::add); + assertEquals(1, queued.size()); + + dashboard.streamUp(A); + dashboard.configChanged(A); + dashboard.configChanged(A); + + assertEquals(2, queued.size()); + queued.forEach(Runnable::run); + verify(serverApi, times(2)).health(A); + assertFalse(queued.isEmpty()); + } + + @Test + void aServerIsConnectingUntilItsFirstAnswerAndOnlyThenDownWithAnUnavailableVersion() throws Exception { + state.setActiveServer(A); + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + create(queued::add); + RecordingEmitter browser = subscribe(); + browser.next(); + + DashboardState before = dashboard.state(); + assertEquals(LinkState.CONNECTING, before.link()); + assertEquals(CheckState.NOT_CHECKED, before.versions().server().checkState()); + + queued.poll().run(); + + DashboardState after = dashboard.state(); + assertEquals(LinkState.DOWN, after.link()); + assertEquals(CheckState.UNAVAILABLE, after.versions().server().checkState()); + assertEquals(List.of("link", "versions"), names(drain(browser))); + } + + @Test + void aStreamDropGoesBackToConnectingNotStraightToDown() { + state.setActiveServer(A); + create(queued::add); + queued.poll().run(); + dashboard.streamUp(A); + + dashboard.streamDown(A); + + assertEquals(LinkState.CONNECTING, dashboard.state().link()); + assertEquals(null, dashboard.state().running()); + } + + @Test + void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws Exception { + state.setActiveServer(A); + VersionStatusDto notChecked = new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null); + doReturn(notChecked).doReturn(notChecked).doReturn(SERVER_VERSION).when(serverApi).serverVersion(A); + create(); + dashboard.streamUp(A); + RecordingEmitter browser = subscribe(); + browser.next(); + clearInvocations(serverApi); + + advance(Duration.ofSeconds(20)); + dashboard.tick(); + verify(serverApi, never()).serverVersion(anyString()); + + advance(Duration.ofSeconds(12)); + dashboard.tick(); + + verify(serverApi, times(1)).serverVersion(A); + assertEquals(CheckState.OK, dashboard.state().versions().server().checkState()); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("versions")).toList(); + assertEquals(1, events.size()); + assertTrue(events.get(0).contains("\"checkState\":\"OK\""), events.get(0)); + } + + @Test + void aFlappingLinkDoesNotRefetchTheServerVersionWithinFiveMinutes() { + state.setActiveServer(A); + create(); + clearInvocations(serverApi); + + dashboard.streamUp(A); + dashboard.streamDown(A); + dashboard.streamUp(A); + + verify(serverApi, never()).serverVersion(anyString()); + } + + @Test + void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChanged() throws Exception { + state.setActiveServer(A); + List one = List.of(new BackupDto("a", "a.zip", 1L, START)); + List two = List.of(new BackupDto("a", "a.zip", 1L, START), new BackupDto("b", "b.zip", 2L, START)); + doReturn(one).when(serverApi).listBackups(A); + create(); + RecordingEmitter browser = subscribe(); + browser.next(); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + assertTrue(names(drain(browser)).stream().noneMatch("backups-changed"::equals)); + + advance(Duration.ofSeconds(30)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + + doReturn(two).when(serverApi).listBackups(A); + advance(Duration.ofSeconds(31)); + dashboard.tick(); + verify(serverApi, times(2)).listBackups(A); + List events = drain(browser).stream().filter(event -> nameOf(event).equals("backups-changed")).toList(); + assertEquals(1, events.size()); + assertTrue(events.get(0).contains("\"at\":\"2026-11-12T10:01:09Z\""), events.get(0)); + + advance(Duration.ofSeconds(61)); + dashboard.tick(); + assertTrue(drain(browser).stream().noneMatch(event -> nameOf(event).equals("backups-changed"))); + } + + @Test + void aLiveLinkNeverChecksTheArchiveListItself() { + state.setActiveServer(A); + create(); + dashboard.streamUp(A); + clearInvocations(serverApi); + + advance(Duration.ofMinutes(5)); + dashboard.tick(); + + verify(serverApi, never()).listBackups(anyString()); + } + + @Test + void aRunThatFinishesWhileDegradedRebaselinesTheArchiveListInsteadOfAnnouncingIt() throws Exception { + state.setActiveServer(A); + List one = List.of(new BackupDto("a", "a.zip", 1L, START)); + List two = List.of(new BackupDto("a", "a.zip", 1L, START), new BackupDto("b", "b.zip", 2L, START)); + doReturn(one).when(serverApi).listBackups(A); + doReturn(BUSY).when(serverApi).health(A); + create(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + RecordingEmitter browser = subscribe(); + browser.next(); + + doReturn(IDLE).when(serverApi).health(A); + doReturn(two).when(serverApi).listBackups(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + advance(Duration.ofSeconds(61)); + dashboard.tick(); + + List names = names(drain(browser)); + assertTrue(names.contains("state")); + assertFalse(names.contains("backups-changed")); + } + + @Test + void aServerThatCameBackAfterBeingDownIsAskedForItsVersionAgainAtOnce() { + state.setActiveServer(A); + create(); + verify(serverApi, times(1)).serverVersion(A); + + doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + assertEquals(LinkState.DOWN, dashboard.state().link()); + clearInvocations(serverApi); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(LinkState.DEGRADED, dashboard.state().link()); + verify(serverApi, times(1)).serverVersion(A); + } + + @Test + void aFailingArchiveListingIsRetriedOnlyOncePerMinute() { + state.setActiveServer(A); + doThrow(new ResourceAccessException("timed out")).when(serverApi).listBackups(A); + create(); + + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + verify(serverApi, times(1)).listBackups(A); + + advance(Duration.ofSeconds(60)); + dashboard.tick(); + verify(serverApi, times(2)).listBackups(A); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java new file mode 100644 index 0000000..b28b7c1 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java @@ -0,0 +1,66 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class SemVerTest { + + private static SemVer v(String text) { + return SemVer.parse(text).orElseThrow(); + } + + @Test + void parsesWithAndWithoutLeadingV() { + assertEquals(new SemVer(0, 1, 0, List.of()), v("0.1.0")); + assertEquals(new SemVer(0, 1, 0, List.of()), v("v0.1.0")); + assertEquals(new SemVer(12, 34, 56, List.of()), v(" v12.34.56 ")); + } + + @Test + void parsesPrereleaseAndIgnoresBuildMetadata() { + assertEquals(new SemVer(1, 0, 0, List.of("rc", "1")), v("v1.0.0-rc.1+build.5")); + assertEquals(0, v("1.0.0+a").compareTo(v("1.0.0+b"))); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "1", "1.2", "v1.2", "1.2.3.4", "latest", "1.2.x", "1.2.3-", "1.2.3-a..b", "vv1.2.3", "1.2.3 beta", "99999999999999999999.0.0"}) + void rejectsInvalidVersions(String text) { + assertEquals(Optional.empty(), SemVer.parse(text)); + } + + @Test + void rejectsNull() { + assertEquals(Optional.empty(), SemVer.parse(null)); + } + + @Test + void comparesNumericallyNotLexically() { + assertTrue(v("0.10.0").compareTo(v("0.9.0")) > 0); + assertTrue(v("1.0.0").compareTo(v("0.99.99")) > 0); + assertTrue(v("0.1.10").compareTo(v("0.1.9")) > 0); + assertTrue(v("0.1.0").compareTo(v("0.2.0")) < 0); + assertEquals(0, v("v0.1.0").compareTo(v("0.1.0"))); + } + + @Test + void ordersPrereleasesPerSemver() { + List ascending = List.of("1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"); + for (int i = 0; i < ascending.size() - 1; i++) { + assertTrue(v(ascending.get(i)).compareTo(v(ascending.get(i + 1))) < 0, ascending.get(i) + " < " + ascending.get(i + 1)); + assertTrue(v(ascending.get(i + 1)).compareTo(v(ascending.get(i))) > 0); + } + } + + @Test + void rendersWithoutPrefixOrMetadata() { + assertEquals("0.2.0", v("v0.2.0").toString()); + assertEquals("1.0.0-rc.1", v("v1.0.0-rc.1+x").toString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java index bd3f4ba..9b41876 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -1,30 +1,40 @@ package wellatleastitried.mediagarrdclient.service; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.http.HttpConnectTimeoutException; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientResponseException; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; +import wellatleastitried.mediagarrdclient.Configuration; import wellatleastitried.mediagarrdclient.api.ApiExceptionHandler; +import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; class ServerApiServiceTest { @@ -32,11 +42,13 @@ private record Exchange(String method, String path, String body) { } private final List exchanges = new ArrayList<>(); - private final ServerApiService service = new ServerApiService(); + private final ServerApiService service = new ServerApiService(Duration.ofHours(6)); private HttpServer server; private String serverUrl; private int status = 200; private String response = "{}"; + private Duration delay = Duration.ZERO; + private final CountDownLatch release = new CountDownLatch(1); @BeforeEach void startServer() throws IOException { @@ -48,6 +60,7 @@ void startServer() throws IOException { @AfterEach void stopServer() { + release.countDown(); server.stop(0); } @@ -61,6 +74,17 @@ void sendsConfigUpdatesWithOmittedFieldsAsNull() { assertEquals(new Exchange("PUT", "/api/v1/config", "{\"backupLocation\":null,\"retentionCount\":5}"), exchanges.getFirst()); } + @Test + void readsTheServerVersionStatusAndIgnoresUnknownFields() { + response = "{\"currentVersion\": \"0.1.0\", \"latestVersion\": \"0.2.0\", \"releaseUrl\": \"https://github.com/MediaGarrd/Server/releases/tag/v0.2.0\"," + + " \"updateAvailable\": true, \"checkState\": \"OK\", \"checkedAt\": \"2026-11-11T18:00:00Z\", \"message\": null, \"extra\": 1}"; + + VersionStatusDto version = service.serverVersion(serverUrl); + + assertEquals(new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, CheckState.OK, Instant.parse("2026-11-11T18:00:00Z"), null), version); + assertEquals(new Exchange("GET", "/api/v1/version", ""), exchanges.getFirst()); + } + @Test void sendsScheduleAsIsoDuration() { response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H30M\"}"; @@ -105,9 +129,95 @@ void fallsBackToTheStatusWhenTheServerSendsNoMessage() { assertEquals(Map.of("error", "MediaGarrd server responded with 502"), new ApiExceptionHandler().serverRejected(e).getBody()); } + @Test + void reportsABackupRunThatOutlastsTheTimeout() { + ServerApiService shortTimeout = new ServerApiService(Duration.ofMillis(200)); + delay = Duration.ofSeconds(2); + + BackupRunTimeoutException e = assertThrows(BackupRunTimeoutException.class, () -> shortTimeout.triggerBackup(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().backupRunTimedOut(e); + + assertEquals("POST", exchanges.get(0).method()); + assertEquals("/api/v1/backups/run", exchanges.get(0).path()); + assertEquals(HttpStatus.GATEWAY_TIMEOUT, forwarded.getStatusCode()); + assertTrue(e.getMessage().contains("still running on the server")); + } + + @Test + void waitsForABackupRunWithinTheTimeout() { + delay = Duration.ofMillis(300); + + service.triggerBackup(serverUrl); + + assertEquals(1, exchanges.size()); + } + + @Test + void rejectsABackupRunTimeoutBelowTheMinimum() { + assertRejected(null); + assertRejected(Duration.ofSeconds(-1)); + assertRejected(Duration.ZERO); + IllegalStateException e = assertRejected(Duration.ofSeconds(59)); + assertTrue(e.getMessage().contains("at least PT1M")); + Configuration ok = new Configuration(); + ok.setBackupRunTimeout(Duration.ofMinutes(1)); + new ServerApiService(ok); + } + + private static IllegalStateException assertRejected(Duration timeout) { + Configuration properties = new Configuration(); + properties.setBackupRunTimeout(timeout); + return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties)); + } + + @Test + void mapsAReadTimeoutOnTheOrdinaryClientsToGatewayTimeout() { + delay = Duration.ofSeconds(8); + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health(serverUrl)); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, new ApiExceptionHandler().serverUnreachable(e).getStatusCode()); + assertEquals(Map.of("error", "MediaGarrd server did not respond in time"), new ApiExceptionHandler().serverUnreachable(e).getBody()); + } + + @Test + void survivesACyclicCauseChain() { + Exception a = new Exception("a"); + Exception b = new Exception("b", a); + a.initCause(b); + + assertFalse(RequestTimeouts.isTimeout(a)); + assertFalse(RequestTimeouts.isReadTimeout(a)); + } + + @Test + void mapsAConnectionRefusedToBadGateway() { + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health("http://127.0.0.1:1")); + + assertEquals(HttpStatus.BAD_GATEWAY, new ApiExceptionHandler().serverUnreachable(e).getStatusCode()); + } + + @Test + void treatsAConnectTimeoutAsATimeoutButNotAsAReadTimeout() { + Throwable connect = new ResourceAccessException("x", new IOException("y", new HttpConnectTimeoutException("z"))); + + assertTrue(RequestTimeouts.isTimeout(connect)); + assertFalse(RequestTimeouts.isReadTimeout(connect)); + assertEquals(HttpStatus.GATEWAY_TIMEOUT, new ApiExceptionHandler().serverUnreachable((ResourceAccessException) connect).getStatusCode()); + } + + @Test + void doesNotReportAnUnreachableServerAsATimeout() { + assertThrows(ResourceAccessException.class, () -> service.triggerBackup("http://127.0.0.1:1")); + } + private void handle(HttpExchange exchange) throws IOException { String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); exchanges.add(new Exchange(exchange.getRequestMethod(), exchange.getRequestURI().getRawPath(), body)); + try { + release.await(delay.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); if (status == 204) { diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java index fd527b3..af19981 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -5,7 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -19,12 +21,21 @@ import java.time.Duration; import java.util.List; import java.util.Optional; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.scheduling.annotation.Scheduled; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.net.httpserver.HttpServer; @@ -32,6 +43,7 @@ import wellatleastitried.mediagarrdclient.Configuration; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; +@Timeout(10) class ServerDiscoveryServiceTest { private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; @@ -91,7 +103,141 @@ void connectsThePreferredServerOnlyWhileNoneIsSelected() { when(state.getActiveServer()).thenReturn("http://other:38471"); discovery.connectPreferredServer(); - verify(state, times(1)).setActiveServer(url(mediaGarrd)); + verify(state, times(1)).setActiveServerIfBlank(url(mediaGarrd)); + } + + @Test + void retriesQuicklyWhileNoServerIsSelected() throws NoSuchMethodException { + Scheduled schedule = ServerDiscoveryService.class.getMethod("connectPreferredServer").getAnnotation(Scheduled.class); + + assertTrue(schedule.fixedDelay() >= 1_000 && schedule.fixedDelay() <= 5_000, + "connectPreferredServer must use a numeric fixedDelay of 1-5 s, found " + schedule.fixedDelay() + " ms (fixedDelayString='" + schedule.fixedDelayString() + "')"); + assertTrue(schedule.initialDelay() >= 0 && schedule.initialDelay() <= 5_000, + "connectPreferredServer must use a numeric initialDelay of at most 5 s, found " + schedule.initialDelay() + " ms (initialDelayString='" + schedule.initialDelayString() + "')"); + } + + @Test + void keepsRetryingUntilThePreferredServerComesUp() throws IOException { + int freePort; + try (java.net.ServerSocket probe = new java.net.ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + freePort = probe.getLocalPort(); + } + configuration.setPreferredServerIp("127.0.0.1:" + freePort); + + discovery.connectPreferredServer(); + discovery.connectPreferredServer(); + verify(state, never()).setActiveServerIfBlank(anyString()); + + HttpServer late = serve(HEALTH, freePort); + try { + discovery.connectPreferredServer(); + verify(state, times(1)).setActiveServerIfBlank("http://127.0.0.1:" + freePort); + } finally { + late.stop(0); + } + } + + @Test + void abandonsAHangingResolveAtTheDeadlineAndNeverOverlapsAttempts() throws InterruptedException { + CountDownLatch release = new CountDownLatch(1); + AtomicInteger attempts = new AtomicInteger(); + ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); + Duration deadline = Duration.ofMillis(300); + ServerDiscoveryService hanging = new ServerDiscoveryService(configuration, state, new ObjectMapper(), pool, deadline) { + @Override + public Optional resolvePreferredServer() { + attempts.incrementAndGet(); + long end = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + while (release.getCount() > 0 && System.nanoTime() < end) { + try { + release.await(50, TimeUnit.MILLISECONDS); + } catch (InterruptedException ignored) { + } + } + return Optional.empty(); + } + }; + try { + long start = System.nanoTime(); + hanging.connectPreferredServer(); + long elapsed = Duration.ofNanos(System.nanoTime() - start).toMillis(); + assertTrue(elapsed < deadline.toMillis() + 1_500, "tick blocked for " + elapsed + " ms"); + + hanging.connectPreferredServer(); + hanging.connectPreferredServer(); + assertEquals(1, attempts.get()); + + release.countDown(); + long waitUntil = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (attempts.get() < 2 && System.nanoTime() < waitUntil) { + hanging.connectPreferredServer(); + Thread.sleep(20); + } + assertEquals(2, attempts.get()); + } finally { + release.countDown(); + hanging.shutdown(); + pool.shutdownNow(); + } + } + + @Test + void anAttemptCancelledBeforeItStartsDoesNotBlockLaterAttempts() { + List queued = new CopyOnWriteArrayList<>(); + ExecutorService deferred = new AbstractExecutorService() { + @Override + public void execute(Runnable command) { + queued.add(command); + } + + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + }; + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, new ObjectMapper(), deferred, Duration.ofMillis(100)); + + service.connectPreferredServer(); + assertEquals(1, queued.size()); + service.connectPreferredServer(); + + assertEquals(2, queued.size(), "the guard stayed set after the attempt was cancelled before starting"); + queued.forEach(Runnable::run); + verify(state, never()).setActiveServerIfBlank(anyString()); + } + + @Test + void doesNotProbeOnceAServerIsSelected() throws IOException { + AtomicInteger requests = new AtomicInteger(); + mediaGarrd.stop(0); + mediaGarrd = serve(HEALTH, 0, requests); + configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + when(state.getActiveServer()).thenReturn("http://other:38471"); + + discovery.connectPreferredServer(); + discovery.connectPreferredServer(); + + assertEquals(0, requests.get()); + verify(state, never()).setActiveServerIfBlank(anyString()); } @Test @@ -143,8 +289,17 @@ void rejectsInputWithoutAHost() { } private static HttpServer serve(String body) throws IOException { - HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + return serve(body, 0); + } + + private static HttpServer serve(String body, int port) throws IOException { + return serve(body, port, new AtomicInteger()); + } + + private static HttpServer serve(String body, int port, AtomicInteger requests) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); server.createContext("/", exchange -> { + requests.incrementAndGet(); byte[] bytes = body.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, bytes.length); try (OutputStream out = exchange.getResponseBody()) { diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java new file mode 100644 index 0000000..fb8dd88 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java @@ -0,0 +1,451 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.client.ResourceAccessException; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.service.ClientEventBroadcasterTest.RecordingEmitter; +import wellatleastitried.mediagarrdclient.service.ServerEventStreamService.Timing; + +@Timeout(30) +class ServerEventStreamServiceTest { + + private static final ObjectMapper MAPPER = JsonMapper.builder() + .findAndAddModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .build(); + private static final Timing FAST = new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMillis(400), Duration.ZERO); + + interface Behavior { + void handle(HttpExchange exchange, int connection) throws Exception; + } + + static final class FakeServer { + + final HttpServer server; + final ExecutorService executor = Executors.newCachedThreadPool(); + final BlockingQueue connections = new LinkedBlockingQueue<>(); + final AtomicInteger count = new AtomicInteger(); + final CountDownLatch release = new CountDownLatch(1); + + FakeServer(Behavior behavior) throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.setExecutor(executor); + server.createContext("/api/v1/events", exchange -> { + int connection = count.incrementAndGet(); + connections.add(System.nanoTime()); + try { + behavior.handle(exchange, connection); + } catch (Exception e) { + exchange.close(); + } finally { + exchange.close(); + } + }); + server.start(); + } + + String url() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + long awaitConnection() throws InterruptedException { + Long at = connections.poll(10, TimeUnit.SECONDS); + assertNotNull(at, "the fake server was never contacted"); + return at; + } + + void stop() { + release.countDown(); + server.stop(0); + executor.shutdownNow(); + } + } + + @TempDir + Path tempDir; + + private ClientStateService state; + private ClientEventBroadcaster broadcaster; + private DashboardService dashboard; + private ServerApiService serverApi; + private ExecutorService refreshes; + private ServerEventStreamService service; + private RecordingEmitter browser; + private final List servers = new ArrayList<>(); + + @BeforeEach + void setUp() { + Configuration configuration = new Configuration(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + broadcaster = new ClientEventBroadcaster(Duration.ofMinutes(10), 32, 64, Duration.ofMinutes(5), Duration.ofMinutes(6), runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + return thread; + }, RecordingEmitter::new); + serverApi = mock(ServerApiService.class); + when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); + when(serverApi.serverVersion(anyString())).thenThrow(new ResourceAccessException("refused")); + UpdateCheckService updateCheck = mock(UpdateCheckService.class); + when(updateCheck.status()).thenReturn(new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null)); + refreshes = Executors.newSingleThreadExecutor(); + dashboard = new DashboardService(state, broadcaster, serverApi, new VersionService(updateCheck, serverApi), updateCheck, MAPPER, refreshes, Clock.systemUTC()); + } + + @AfterEach + void tearDown() { + if (service != null) { + service.shutdown(); + } + broadcaster.shutdown(); + refreshes.shutdownNow(); + servers.forEach(FakeServer::stop); + } + + private FakeServer fake(Behavior behavior) throws IOException { + FakeServer fake = new FakeServer(behavior); + servers.add(fake); + return fake; + } + + private void startService(Timing timing) { + service = new ServerEventStreamService(state, dashboard, MAPPER, timing); + browser = (RecordingEmitter) dashboard.subscribe().orElseThrow(); + service.start(); + } + + private static void frame(OutputStream out, String text) throws IOException { + out.write(text.getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + private static OutputStream open(HttpExchange exchange) throws IOException { + exchange.getResponseHeaders().add("Content-Type", "text/event-stream"); + exchange.sendResponseHeaders(200, 0); + OutputStream out = exchange.getResponseBody(); + frame(out, ": connected\n\n"); + return out; + } + + private static Behavior holdOpen(CountDownLatch closed, String... frames) { + return (exchange, connection) -> { + OutputStream out = open(exchange); + for (String text : frames) { + frame(out, text); + } + try { + while (true) { + Thread.sleep(10); + frame(out, ": keep\n\n"); + } + } catch (IOException e) { + closed.countDown(); + } + }; + } + + private List collectUntil(String marker) throws InterruptedException { + List seen = new ArrayList<>(); + while (true) { + seen.add(browser.next()); + if (seen.get(seen.size() - 1).contains(marker)) { + return seen; + } + } + } + + @Test + void forwardsRunEventsAndIgnoresEverythingElse() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event:state\ndata:{\"running\":false,\"at\":\"t0\"}\n\n"); + frame(out, "event: ping\ndata: {}\n\n"); + frame(out, "event: surprise\ndata: {\"x\":1}\n\n"); + frame(out, "event: run-started\ndata: not-json\n\n"); + frame(out, "event: run-started\r\ndata: {\"running\":true,\"startedAt\":\"t1\"}\r\n\r\n"); + frame(out, "event: backups-changed\ndata: not-json\n\n"); + frame(out, "event: backups-changed\ndata: {\"at\":\"t3\"}\n\n"); + frame(out, "event: config-changed\ndata: {\"at\":\"t4\"}\n\n"); + frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\",\"startedAt\":\"t1\",\"finishedAt\":\"t2\"}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:run-finished"); + List relevant = seen.stream().filter(event -> !event.contains("event:versions") && !(event.contains("event:link") && event.contains("\"state\":\"DOWN\""))).toList(); + List names = relevant.stream().map(ServerEventStreamServiceTest::nameOf).toList(); + assertEquals(List.of("snapshot", "snapshot", "link", "state", "run-started", "backups-changed", "run-finished"), names); + assertTrue(relevant.get(0).contains("\"activeServer\":null")); + assertTrue(relevant.get(1).contains("\"activeServer\":\"" + fake.url() + "\"") && relevant.get(1).contains("\"link\":\"CONNECTING\"")); + assertTrue(relevant.get(2).contains("\"state\":\"LIVE\"") && relevant.get(2).contains(fake.url())); + assertTrue(relevant.get(4).contains("\"startedAt\":\"t1\"")); + assertEquals("event:backups-changed\ndata:{\"at\":\"t3\"}\n\n", relevant.get(5)); + assertTrue(relevant.get(6).contains("\"status\":\"PARTIAL\"")); + } + + private static String nameOf(String event) { + for (String line : event.split("\n")) { + if (line.startsWith("event:")) { + return line.substring("event:".length()); + } + } + return ""; + } + + private static void hold() throws Exception { + new CountDownLatch(1).await(20, TimeUnit.SECONDS); + } + + @Test + void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); + if (connection > 1) { + hold(); + } + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + fake.awaitConnection(); + List seen = collectUntil("\"running\":false"); + int connectedAt = -1; + for (int i = 0; i < seen.size(); i++) { + if (seen.get(i).contains("event:link") && seen.get(i).contains("\"state\":\"LIVE\"")) { + assertEquals(-1, connectedAt, "link reported connected twice"); + connectedAt = i; + } + } + assertTrue(connectedAt >= 0); + assertTrue(seen.subList(connectedAt, seen.size()).stream().noneMatch(event -> event.contains("event:link") && event.contains("\"state\":\"DOWN\""))); + } + + @Test + void retriesWithBackoffAfterAFailureAndReportsTheLinkDown() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection < 3) { + exchange.sendResponseHeaders(500, -1); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":true}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:state"); + assertEquals(3, fake.count.get()); + assertTrue(seen.stream().anyMatch(event -> event.contains("event:link") && event.contains("\"state\":\"LIVE\""))); + } + + @Test + void rejectsAResponseThatIsNotAnEventStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.getResponseHeaders().add("Content-Type", "text/html"); + exchange.sendResponseHeaders(200, 0); + frame(exchange.getResponseBody(), "event: state\ndata: {\"running\":true}\n\n"); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:state"); + assertTrue(seen.get(seen.size() - 1).contains("\"running\":false")); + assertEquals(2, fake.count.get()); + } + + @Test + void anOldServerWithoutTheStreamIsRetriedOnlyAfterTheLongInterval() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.sendResponseHeaders(404, -1); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 350, "retried too early"); + collectUntil("event:state"); + } + + @Test + void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Exception { + CountDownLatch oldClosed = new CountDownLatch(1); + FakeServer old = fake(holdOpen(oldClosed, "event: state\ndata: {\"running\":true}\n\n")); + FakeServer next = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":false}\n\n")); + state.setActiveServer(old.url()); + startService(FAST); + collectUntil("\"running\":true"); + + state.setActiveServer(next.url()); + + assertTrue(oldClosed.await(10, TimeUnit.SECONDS), "the old stream was not closed"); + List seen = collectUntil("\"running\":false"); + assertTrue(seen.stream().anyMatch(event -> event.contains("event:snapshot") && event.contains("\"activeServer\":\"" + next.url() + "\"") && event.contains("\"running\":null"))); + assertTrue(seen.stream().anyMatch(event -> event.contains("event:link") && event.contains("\"state\":\"LIVE\"") && event.contains(next.url()))); + assertEquals(1, old.count.get()); + } + + @Test + void clearingTheActiveServerStopsTheStreamAndDoesNotReconnect() throws Exception { + CountDownLatch closed = new CountDownLatch(1); + FakeServer fake = fake(holdOpen(closed, "event: state\ndata: {\"running\":true}\n\n")); + state.setActiveServer(fake.url()); + startService(FAST); + collectUntil("\"running\":true"); + + state.setActiveServer(""); + + assertTrue(closed.await(10, TimeUnit.SECONDS)); + String cleared = browser.nextContaining("\"activeServer\":null"); + assertTrue(cleared.contains("event:snapshot") && cleared.contains("\"link\":\"DOWN\""), cleared); + assertEquals(1, fake.count.get()); + } + + @Test + void doesNotConnectWithoutAnActiveServer() throws Exception { + startService(FAST); + + String snapshot = browser.next(); + assertTrue(snapshot.contains("event:snapshot") && snapshot.contains("\"link\":\"DOWN\"")); + assertNull(browser.sent.poll(200, TimeUnit.MILLISECONDS)); + } + + @Test + void reconnectsAStreamThatGoesSilent() throws Exception { + Timing quick = new Timing(Duration.ofSeconds(5), Duration.ofMillis(200), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMillis(400), Duration.ZERO); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(quick); + + fake.awaitConnection(); + fake.awaitConnection(); + List seen = collectUntil("\"running\":false"); + assertFalse(seen.isEmpty()); + } + + @Test + void startsOnItsOwnForAServerRestoredFromTheStateFile() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":true}\n\n")); + state.setActiveServer(fake.url()); + Configuration configuration = new Configuration(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, MAPPER); + + startService(FAST); + + fake.awaitConnection(); + collectUntil("\"running\":true"); + } + + @Test + void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() throws Exception { + Timing slowRetry = new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(400), Duration.ofMinutes(1)); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + }); + state.setActiveServer(fake.url()); + + startService(slowRetry); + + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + long third = fake.awaitConnection(); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 250, "reconnected too fast"); + assertTrue(TimeUnit.NANOSECONDS.toMillis(third - second) >= 250, "reconnected too fast"); + } + + @Test + void aConfigChangedEventMakesTheClientRefetchTheServerHealthOnce() throws Exception { + doReturn(new ServerStatusDto(true, false, 5, Duration.ofHours(6))).when(serverApi).health(anyString()); + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":false}\n\n"); + Thread.sleep(2000); + frame(out, "event: config-changed\ndata: {\"at\":\"t\"}\n\n"); + hold(); + }); + state.setActiveServer(fake.url()); + + startService(FAST); + + browser.nextContaining("event:config"); + Thread.sleep(800); + clearInvocations(serverApi); + + verify(serverApi, timeout(10_000).times(1)).health(fake.url()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java new file mode 100644 index 0000000..4310a64 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java @@ -0,0 +1,322 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; + +class UpdateCheckServiceTest { + + private static final Instant NOW = Instant.parse("2026-11-11T18:00:00Z"); + + private final List requests = new ArrayList<>(); + private final List userAgents = new ArrayList<>(); + private final Configuration properties = new Configuration(); + private HttpServer server; + private int status = 200; + private String rateLimitRemaining; + private String response = ""; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + properties.setGithubApiBaseUrl("http://127.0.0.1:" + server.getAddress().getPort() + "/"); + properties.setUpdateRepository("MediaGarrd/Client"); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + private UpdateCheckService service(String currentVersion) { + return new UpdateCheckService(properties, currentVersion, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static String release(String tag) { + return "{\"tag_name\": \"" + tag + "\", \"html_url\": \"https://github.com/MediaGarrd/Client/releases/tag/" + tag + + "\", \"draft\": false, \"prerelease\": false, \"id\": 1}"; + } + + @Test + void reportsNotCheckedBeforeTheFirstRun() { + VersionStatusDto result = service("0.1.0").status(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null), result); + assertTrue(requests.isEmpty()); + } + + @Test + void tellsListenersOnlyWhenTheStatusChanges() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + List seen = new ArrayList<>(); + service.addStatusListener(seen::add); + + service.check(); + service.check(); + + assertEquals(1, seen.size()); + assertEquals(CheckState.OK, seen.get(0).checkState()); + assertTrue(seen.get(0).updateAvailable()); + + response = release("v0.3.0"); + service.check(); + + assertEquals(2, seen.size()); + assertEquals("0.3.0", seen.get(1).latestVersion()); + } + + @Test + void aFailingListenerDoesNotBreakTheCheckOrTheOthers() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + List seen = new ArrayList<>(); + service.addStatusListener(ignored -> { + throw new IllegalStateException("boom"); + }); + service.addStatusListener(seen::add); + + service.check(); + + assertEquals(1, seen.size()); + assertEquals(CheckState.OK, service.status().checkState()); + } + + @Test + void reportsAnUpdateWhenTheLatestReleaseIsNewer() { + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.2.0", true, CheckState.OK, NOW, null), service.status()); + assertEquals(List.of("/repos/MediaGarrd/Client/releases/latest"), requests); + assertEquals(List.of("MediaGarrd-Client/0.1.0"), userAgents); + } + + @Test + void reportsUpToDateWhenTheLatestReleaseIsTheSameVersion() { + response = release("v0.1.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertEquals("0.1.0", service.status().latestVersion()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void neverReportsAnOlderReleaseAsAnUpdate() { + response = release("v0.1.0"); + UpdateCheckService service = service("0.2.0"); + + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void treatsAPrereleaseOfTheRunningVersionAsOlder() { + response = release("v0.2.0-rc.1"); + UpdateCheckService service = service("0.2.0"); + + service.check(); + + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsNoReleasesOnNotFound() { + status = 404; + response = "{\"message\": \"Not Found\"}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(new VersionStatusDto("0.1.0", null, null, false, CheckState.NO_RELEASES, NOW, null), service.status()); + } + + @Test + void reportsRateLimitingAsAnError() { + status = 403; + rateLimitRemaining = "0"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub rate limit reached", service.status().message()); + assertFalse(service.status().updateAvailable()); + + status = 429; + rateLimitRemaining = null; + service.check(); + assertEquals("GitHub rate limit reached", service.status().message()); + } + + @Test + void reportsAForbiddenResponseWithoutAnExhaustedLimitAsAPlainHttpError() { + status = 403; + UpdateCheckService service = service("0.1.0"); + + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 403", service.status().message()); + + rateLimitRemaining = "12"; + service.check(); + assertEquals("GitHub returned HTTP 403", service.status().message()); + } + + @Test + void rejectsCheckIntervalsBelowOneHour() { + properties.setUpdateCheckInterval(Duration.ofMinutes(59)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> service("0.1.0")); + assertTrue(failure.getMessage().contains("at least PT1H")); + + properties.setUpdateCheckInterval(Duration.ZERO); + assertThrows(IllegalStateException.class, () -> service("0.1.0")); + + properties.setUpdateCheckInterval(Duration.ofHours(1)); + service("0.1.0"); + } + + @Test + void reportsServerErrorsAsAnError() { + status = 500; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub returned HTTP 500", service.status().message()); + assertEquals(NOW, service.status().checkedAt()); + } + + @Test + void reportsAnUnreachableGithubAsAnErrorWithoutThrowing() { + server.stop(0); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("GitHub is unreachable", service.status().message()); + } + + @Test + void reportsMalformedResponsesAsAnError() { + response = "not json"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + } + + @Test + void reportsAnUnrecognizedTagAsAnError() { + response = release("nightly"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(CheckState.ERROR, service.status().checkState()); + assertEquals("Latest release has an unrecognized version tag", service.status().message()); + } + + @Test + void reportsAnErrorWithoutCallingGithubWhenTheCurrentVersionIsUnknown() { + response = release("v9.9.9"); + + for (String unknown : new String[] {null, "unspecified"}) { + UpdateCheckService service = service(unknown); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + assertFalse(service.status().updateAvailable()); + assertEquals("Current version is unknown", service.status().message()); + } + assertTrue(requests.isEmpty()); + } + + @Test + void buildsTheReleaseUrlWhenGithubOmitsIt() { + response = "{\"tag_name\": \"v0.3.0\"}"; + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals("https://github.com/MediaGarrd/Client/releases/tag/v0.3.0", service.status().releaseUrl()); + } + + @Test + void recoversOnTheNextCheckAfterAFailure() { + status = 500; + UpdateCheckService service = service("0.1.0"); + service.check(); + assertEquals(CheckState.ERROR, service.status().checkState()); + + status = 200; + response = release("v0.2.0"); + service.check(); + + assertEquals(CheckState.OK, service.status().checkState()); + assertTrue(service.status().updateAvailable()); + assertNull(service.status().message()); + } + + @Test + void usesTheConfiguredRepository() { + properties.setUpdateRepository("someone/else"); + response = release("v0.2.0"); + UpdateCheckService service = service("0.1.0"); + + service.check(); + + assertEquals(List.of("/repos/someone/else/releases/latest"), requests); + } + + private void handle(HttpExchange exchange) throws IOException { + requests.add(exchange.getRequestURI().getPath()); + userAgents.add(exchange.getRequestHeaders().getFirst("User-Agent")); + byte[] body = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (rateLimitRemaining != null) { + exchange.getResponseHeaders().add("X-RateLimit-Remaining", rateLimitRemaining); + } + exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); + if (body.length > 0) { + exchange.getResponseBody().write(body); + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java new file mode 100644 index 0000000..6cb5e16 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java @@ -0,0 +1,236 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; + +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; + +class VersionServiceTest { + + private static final Instant NOW = Instant.parse("2026-11-11T18:00:00Z"); + private static final VersionStatusDto CLIENT = new VersionStatusDto("0.1.0", "0.1.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.1.0", false, CheckState.OK, NOW, null); + private static final VersionStatusDto SERVER = new VersionStatusDto("0.1.0", "0.2.0", "https://github.com/MediaGarrd/Server/releases/tag/v0.2.0", true, CheckState.OK, NOW, null); + private static final String URL = "http://server:38471"; + + private final AtomicReference now = new AtomicReference<>(NOW); + private final Clock clock = new Clock() { + @Override + public java.time.ZoneId getZone() { + return ZoneId.of("UTC"); + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + private final UpdateCheckService updateCheckService = mock(UpdateCheckService.class); + private final ServerApiService serverApiService = mock(ServerApiService.class); + private final VersionService service = new VersionService(updateCheckService, serverApiService, clock); + + VersionServiceTest() { + when(updateCheckService.status()).thenReturn(CLIENT); + } + + @Test + void leavesTheServerOutUntilOneIsSelectedAndNeverCallsTheServerForIt() { + assertNull(service.versions().server()); + assertFalse(service.needsRefresh()); + assertFalse(service.refresh()); + service.select(" "); + + assertNull(service.versions().server()); + verify(serverApiService, never()).serverVersion(anyString()); + } + + @Test + void aSelectedServerIsPendingUntilItsVersionIsFetched() { + assertTrue(service.select(URL)); + + assertEquals(CheckState.NOT_CHECKED, service.versions().server().checkState()); + assertTrue(service.needsRefresh()); + assertFalse(service.select(URL)); + } + + @Test + void cachesTheFetchedVersionWithoutAskingTheServerAgain() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + + assertTrue(service.refresh()); + + assertEquals(new VersionsDto(CLIENT, SERVER), service.versions()); + assertEquals(new VersionsDto(CLIENT, SERVER), service.versions()); + assertFalse(service.needsRefresh()); + verify(serverApiService, times(1)).serverVersion(URL); + } + + @Test + void refetchesAtMostHourlyAndAtOnceAfterAnInvalidation() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + now.set(NOW.plus(Duration.ofMinutes(59))); + assertFalse(service.needsRefresh()); + now.set(NOW.plus(Duration.ofHours(1))); + assertTrue(service.needsRefresh()); + + service.refresh(); + assertFalse(service.needsRefresh()); + assertFalse(service.invalidate(false)); + assertFalse(service.needsRefresh()); + now.set(now.get().plus(Duration.ofMinutes(6))); + assertTrue(service.invalidate(false)); + assertTrue(service.needsRefresh()); + } + + @Test + void aServerThatHasNotCheckedYetIsAskedAgainAfterThirtySeconds() { + VersionStatusDto notChecked = new VersionStatusDto("0.1.0", null, null, false, CheckState.NOT_CHECKED, null, null); + when(serverApiService.serverVersion(URL)).thenReturn(notChecked).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + now.set(NOW.plus(Duration.ofSeconds(29))); + assertFalse(service.needsRefresh()); + now.set(NOW.plus(Duration.ofSeconds(30))); + assertTrue(service.needsRefresh()); + assertTrue(service.refresh()); + + assertEquals(CheckState.OK, service.versions().server().checkState()); + now.set(NOW.plus(Duration.ofMinutes(10))); + assertFalse(service.needsRefresh()); + } + + @Test + void aServerThatReportedAnErrorIsAskedAgainAfterFiveMinutes() { + VersionStatusDto failed = new VersionStatusDto("0.1.0", null, null, false, CheckState.ERROR, NOW, "GitHub is unreachable"); + when(serverApiService.serverVersion(URL)).thenReturn(failed); + service.select(URL); + service.refresh(); + + now.set(NOW.plus(Duration.ofMinutes(4))); + assertFalse(service.needsRefresh()); + now.set(NOW.plus(Duration.ofMinutes(5))); + assertTrue(service.needsRefresh()); + assertTrue(service.invalidate(false)); + } + + @Test + void aFailedFirstAttemptTurnsThePendingVersionIntoUnavailableOnce() { + assertFalse(service.markUnreachable()); + service.select(URL); + + assertTrue(service.markUnreachable()); + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + assertFalse(service.markUnreachable()); + assertTrue(service.invalidate(false)); + } + + @Test + void aFetchedVersionIsNotReplacedByAFailedLaterAttempt() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + assertFalse(service.markUnreachable()); + assertEquals(SERVER, service.versions().server()); + } + + @Test + void reportsWhetherARefetchChangedAnything() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + + assertTrue(service.refresh()); + assertFalse(service.refresh()); + } + + @Test + void switchingServersDropsTheCachedVersionAndIgnoresAnInFlightAnswer() { + when(serverApiService.serverVersion(URL)).thenAnswer(call -> { + service.select("http://other:38471"); + return SERVER; + }); + service.select(URL); + + assertFalse(service.refresh()); + + assertEquals(CheckState.NOT_CHECKED, service.versions().server().checkState()); + } + + @Test + void reportsTheServerAsUnavailableWhenItCannotBeReachedAndRetriesSooner() { + when(serverApiService.serverVersion(URL)).thenThrow(new ResourceAccessException("refused")); + service.select(URL); + + service.refresh(); + + VersionsDto result = service.versions(); + assertEquals(CLIENT, result.client()); + assertEquals(CheckState.UNAVAILABLE, result.server().checkState()); + assertFalse(result.server().updateAvailable()); + now.set(NOW.plus(Duration.ofMinutes(9))); + assertFalse(service.needsRefresh()); + now.set(NOW.plus(Duration.ofMinutes(10))); + assertTrue(service.needsRefresh()); + } + + @Test + void reportsAnOlderServerWithoutTheEndpointAsUnavailable() { + when(serverApiService.serverVersion(URL)) + .thenThrow(new RestClientResponseException("Not Found", 404, "Not Found", null, null, null)); + service.select(URL); + + service.refresh(); + + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + } + + @Test + void reportsAnEmptyServerResponseAsUnavailable() { + when(serverApiService.serverVersion(URL)).thenReturn(null); + service.select(URL); + + service.refresh(); + + assertEquals(CheckState.UNAVAILABLE, service.versions().server().checkState()); + } + + @Test + void recoveringFromARealOutageRefetchesEvenWithinFiveMinutesOfAGoodAnswer() { + when(serverApiService.serverVersion(URL)).thenReturn(SERVER); + service.select(URL); + service.refresh(); + + assertFalse(service.invalidate(false)); + assertTrue(service.invalidate(true)); + assertTrue(service.needsRefresh()); + } +} diff --git a/src/test/js/dashboard-model.test.mjs b/src/test/js/dashboard-model.test.mjs new file mode 100644 index 0000000..501ae08 --- /dev/null +++ b/src/test/js/dashboard-model.test.mjs @@ -0,0 +1,202 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { applyEvent, canLoadBackups, changes, emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; + +const snapshot = (overrides = {}) => ({ + activeServer: 'http://a:38471', + knownServers: ['http://a:38471'], + link: 'LIVE', + running: false, + health: { backupInterval: 'PT6H', backupRetentionCount: 5 }, + versions: { client: { checkState: 'OK' }, server: { checkState: 'OK' } }, + ...overrides, +}); + +const loaded = (overrides) => reduce(emptyState(), 'snapshot', snapshot(overrides)); + +test('a snapshot replaces the whole state and marks it loaded', () => { + const state = loaded(); + assert.equal(state.loaded, true); + assert.equal(state.activeServer, 'http://a:38471'); + assert.deepEqual(state.knownServers, ['http://a:38471']); + assert.equal(state.link, 'LIVE'); + assert.equal(state.running, false); + assert.deepEqual(state.health, { backupInterval: 'PT6H', backupRetentionCount: 5 }); + assert.equal(state.clientReachable, true); +}); + +test('a snapshot normalizes a missing server and unknown run state', () => { + const state = loaded({ activeServer: null, knownServers: undefined, running: null, health: null, versions: null }); + assert.equal(state.activeServer, null); + assert.deepEqual(state.knownServers, []); + assert.equal(state.running, null); + assert.equal(state.health, null); + assert.equal(state.versions, null); +}); + +test('events before the first snapshot are ignored', () => { + const state = emptyState(); + assert.equal(reduce(state, 'state', { running: true }), state); + assert.equal(reduce(state, 'link', { state: 'LIVE' }), state); +}); + +test('run events set the running flag', () => { + let state = loaded(); + state = reduce(state, 'run-started', { running: true, startedAt: 't' }); + assert.equal(state.running, true); + state = reduce(state, 'run-finished', { running: false, status: 'COMPLETED' }); + assert.equal(state.running, false); + state = reduce(state, 'state', { running: true }); + assert.equal(state.running, true); +}); + +test('a link event changes the link and a DOWN link forgets the run state', () => { + let state = loaded({ running: true }); + state = reduce(state, 'link', { server: 'http://a:38471', state: 'DEGRADED' }); + assert.equal(state.link, 'DEGRADED'); + assert.equal(state.running, true); + state = reduce(state, 'link', { server: 'http://a:38471', state: 'DOWN' }); + assert.equal(state.link, 'DOWN'); + assert.equal(state.running, null); +}); + +test('servers, config and versions events update their slices only', () => { + let state = loaded(); + state = reduce(state, 'servers', { knownServers: ['http://a:38471', 'http://b:38471'], activeServer: 'http://a:38471' }); + assert.deepEqual(state.knownServers, ['http://a:38471', 'http://b:38471']); + assert.equal(state.link, 'LIVE'); + state = reduce(state, 'config', { backupInterval: 'PT2H', backupRetentionCount: 9 }); + assert.deepEqual(state.health, { backupInterval: 'PT2H', backupRetentionCount: 9 }); + state = reduce(state, 'versions', { client: null, server: { checkState: 'UNAVAILABLE' } }); + assert.equal(state.versions.server.checkState, 'UNAVAILABLE'); + assert.equal(state.activeServer, 'http://a:38471'); +}); + +test('pings, backup announcements and unknown events leave the state alone', () => { + const state = loaded(); + assert.equal(reduce(state, 'ping', {}), state); + assert.equal(reduce(state, 'backups-changed', { at: 't' }), state); + assert.equal(reduce(state, 'surprise', {}), state); +}); + +test('the client being unreachable is tracked and cleared by any event from the stream', () => { + let state = loaded(); + state = reduce(state, 'client', { reachable: false }); + assert.equal(state.clientReachable, false); + assert.equal(reduce(state, 'client', { reachable: false }), state); + state = reduce(state, 'ping', {}); + assert.equal(state.clientReachable, true); + state = reduce(reduce(state, 'client', { reachable: false }), 'snapshot', snapshot()); + assert.equal(state.clientReachable, true); +}); + +test('nothing happens before the first snapshot', () => { + assert.deepEqual(changes(emptyState(), emptyState(), 'client'), { serverChanged: false, clearBackups: false, refreshBackups: false }); +}); + +test('the first snapshot of a reachable server loads the backups once', () => { + const next = loaded(); + assert.deepEqual(changes(emptyState(), next, 'snapshot'), { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('the first snapshot of a server that is down waits for it to come up', () => { + const down = loaded({ link: 'DOWN' }); + assert.equal(changes(emptyState(), down, 'snapshot').refreshBackups, false); + const up = reduce(down, 'link', { state: 'DEGRADED' }); + assert.equal(changes(down, up, 'link').refreshBackups, true); +}); + +test('a first snapshot without a server loads no backups', () => { + assert.equal(changes(emptyState(), loaded({ activeServer: null, link: 'DOWN' }), 'snapshot').refreshBackups, false); +}); + +test('switching servers clears the table and reloads it only once the new server is up', () => { + const before = loaded(); + const switched = reduce(before, 'snapshot', snapshot({ activeServer: 'http://b:38471', link: 'DOWN', running: null, health: null })); + assert.deepEqual(changes(before, switched, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: false }); + const up = reduce(switched, 'link', { state: 'LIVE' }); + assert.deepEqual(changes(switched, up, 'link'), { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('a switch noticed through an already-up snapshot reloads right away', () => { + const before = loaded(); + const switched = reduce(before, 'snapshot', snapshot({ activeServer: 'http://b:38471' })); + assert.deepEqual(changes(before, switched, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: true }); +}); + +test('clearing the server clears the table without reloading it', () => { + const before = loaded(); + const cleared = reduce(before, 'snapshot', snapshot({ activeServer: null, link: 'DOWN', running: null })); + assert.deepEqual(changes(before, cleared, 'snapshot'), { serverChanged: true, clearBackups: true, refreshBackups: false }); +}); + +test('a run finishing reloads the backups, however it was learned', () => { + const running = loaded({ running: true }); + const viaEvent = reduce(running, 'run-finished', { running: false }); + assert.equal(changes(running, viaEvent, 'run-finished').refreshBackups, true); + const viaState = reduce(running, 'state', { running: false }); + assert.equal(changes(running, viaState, 'state').refreshBackups, true); + const idle = loaded(); + assert.equal(changes(idle, reduce(idle, 'state', { running: false }), 'state').refreshBackups, false); + assert.equal(changes(idle, reduce(idle, 'run-started', {}), 'run-started').refreshBackups, false); +}); + +test('a backups-changed announcement reloads the backups while the server is up', () => { + const state = loaded(); + assert.equal(changes(state, reduce(state, 'backups-changed', {}), 'backups-changed').refreshBackups, true); + const down = loaded({ link: 'DOWN' }); + assert.equal(changes(down, reduce(down, 'backups-changed', {}), 'backups-changed').refreshBackups, false); +}); + +test('coming back from DOWN or from an unreachable client reloads the backups', () => { + const down = loaded({ link: 'DOWN' }); + assert.equal(changes(down, reduce(down, 'link', { state: 'LIVE' }), 'link').refreshBackups, true); + const live = loaded(); + const unreachable = reduce(live, 'client', { reachable: false }); + assert.equal(changes(live, unreachable, 'client').refreshBackups, false); + assert.equal(changes(unreachable, reduce(unreachable, 'client', { reachable: true }), 'client').refreshBackups, true); +}); + +test('a degraded to live move does not reload anything', () => { + const degraded = loaded({ link: 'DEGRADED' }); + assert.equal(changes(degraded, reduce(degraded, 'link', { state: 'LIVE' }), 'link').refreshBackups, false); +}); + +test('config, versions and server list updates never reload the backups', () => { + const state = loaded(); + assert.equal(changes(state, reduce(state, 'config', { backupInterval: 'PT1H', backupRetentionCount: 2 }), 'config').refreshBackups, false); + assert.equal(changes(state, reduce(state, 'versions', {}), 'versions').refreshBackups, false); + assert.equal(changes(state, reduce(state, 'servers', { knownServers: [], activeServer: 'http://a:38471' }), 'servers').refreshBackups, false); +}); + +test('a backups-changed announcement is an effect even though it leaves the state identical', () => { + const state = loaded(); + const result = applyEvent(state, 'backups-changed', { at: 't' }); + assert.equal(result.state, state); + assert.deepEqual(result.effects, { serverChanged: false, clearBackups: false, refreshBackups: true }); +}); + +test('a backups-changed announcement does nothing while the server is not up', () => { + for (const link of ['DOWN', 'CONNECTING']) { + const state = loaded({ link }); + assert.equal(applyEvent(state, 'backups-changed', { at: 't' }).effects.refreshBackups, false); + } +}); + +test('backups may be loaded only for a reachable client with an active server whose link is up', () => { + assert.equal(canLoadBackups(emptyState()), false); + assert.equal(canLoadBackups(loaded()), true); + assert.equal(canLoadBackups(loaded({ link: 'DEGRADED' })), true); + assert.equal(canLoadBackups(loaded({ link: 'DOWN' })), false); + assert.equal(canLoadBackups(loaded({ link: 'CONNECTING' })), false); + assert.equal(canLoadBackups(loaded({ activeServer: null })), false); + assert.equal(canLoadBackups(reduce(loaded(), 'client', { reachable: false })), false); +}); + +test('a connecting link forgets the run state and a first answer reloads the backups', () => { + const live = loaded({ running: true }); + const connecting = reduce(live, 'link', { state: 'CONNECTING' }); + assert.equal(connecting.running, null); + const up = reduce(connecting, 'link', { state: 'DEGRADED' }); + assert.equal(changes(connecting, up, 'link').refreshBackups, true); +}); diff --git a/src/test/js/reachability.test.mjs b/src/test/js/reachability.test.mjs new file mode 100644 index 0000000..5f62ad1 --- /dev/null +++ b/src/test/js/reachability.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { createReachability } from '../../main/resources/static/js/reachability.js'; + +function harness() { + const changes = []; + const timers = new Map(); + let next = 1; + const reachability = createReachability({ + graceMs: 8000, + onChange: (reachable) => changes.push(reachable), + setTimer: (callback, ms) => { + const id = next++; + timers.set(id, { callback, ms }); + return id; + }, + clearTimer: (id) => timers.delete(id), + }); + const fire = () => [...timers.values()].forEach((timer) => { timers.clear(); timer.callback(); }); + return { reachability, changes, timers, fire }; +} + +test('a transient error followed by open never declares the client unreachable', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + assert.equal(timers.size, 1); + assert.deepEqual([...timers.values()].map((timer) => timer.ms), [8000]); + reachability.alive(); + fire(); + assert.deepEqual(changes, [true]); + assert.equal(timers.size, 0); +}); + +test('an error that is not followed by open declares the client unreachable after the grace period', () => { + const { reachability, changes, fire } = harness(); + reachability.failed(false); + assert.deepEqual(changes, []); + fire(); + assert.deepEqual(changes, [false]); + reachability.alive(); + assert.deepEqual(changes, [false, true]); +}); + +test('repeated errors during the grace period do not extend it', () => { + const { reachability, timers } = harness(); + reachability.failed(false); + reachability.failed(false); + reachability.failed(false); + assert.equal(timers.size, 1); +}); + +test('a closed stream is declared unreachable at once and cancels a pending grace timer', () => { + const { reachability, changes, timers } = harness(); + reachability.failed(false); + reachability.failed(true); + assert.deepEqual(changes, [false]); + assert.equal(timers.size, 0); +}); + +test('any sign of life after a pending error cancels it', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + reachability.alive(); + reachability.failed(false); + assert.equal(timers.size, 1); + fire(); + assert.deepEqual(changes, [true, false]); +}); + +test('cancelling drops a pending grace timer without reporting anything', () => { + const { reachability, changes, timers, fire } = harness(); + reachability.failed(false); + reachability.cancel(); + fire(); + assert.equal(timers.size, 0); + assert.deepEqual(changes, []); +}); diff --git a/src/test/js/view-model.test.mjs b/src/test/js/view-model.test.mjs new file mode 100644 index 0000000..3a3f8ba --- /dev/null +++ b/src/test/js/view-model.test.mjs @@ -0,0 +1,142 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; +import { classifyVersion, linkView, planKnown, versionsView } from '../../main/resources/static/js/view-model.js'; + +const loaded = (overrides = {}) => reduce(emptyState(), 'snapshot', { + activeServer: 'http://a:38471', + knownServers: ['http://a:38471'], + link: 'LIVE', + running: false, + health: { backupInterval: 'PT6H', backupRetentionCount: 5 }, + versions: null, + ...overrides, +}); + +test('before the first snapshot the page says it is connecting', () => { + const view = linkView(emptyState()); + assert.deepEqual(view.badge, { kind: 'checking', label: 'Connecting…' }); + assert.equal(view.showDetails, false); +}); + +test('a live server shows its details and the host in the badge', () => { + const view = linkView(loaded({ running: true })); + assert.deepEqual(view.badge, { kind: 'ok', label: 'a:38471' }); + assert.equal(view.showDetails, true); + assert.equal(view.url, 'http://a:38471'); + assert.equal(view.interval, '6h'); + assert.equal(view.retention, '5 archives'); + assert.equal(view.running, true); + assert.equal(view.degraded, false); +}); + +test('a degraded server looks connected but says live updates are unavailable', () => { + const view = linkView(loaded({ link: 'DEGRADED' })); + assert.equal(view.badge.kind, 'ok'); + assert.equal(view.showDetails, true); + assert.equal(view.degraded, true); +}); + +test('a live server with no health yet shows placeholders and idle', () => { + const view = linkView(loaded({ health: null, running: null })); + assert.equal(view.interval, '—'); + assert.equal(view.retention, '—'); + assert.equal(view.running, false); +}); + +test('a down server names itself and is not shown as connected', () => { + const view = linkView(loaded({ link: 'DOWN', running: null })); + assert.deepEqual(view.badge, { kind: 'down', label: 'Unreachable' }); + assert.equal(view.showDetails, false); + assert.equal(view.message, 'http://a:38471 is not responding.'); +}); + +test('no active server reads as not connected', () => { + const view = linkView(loaded({ activeServer: null, link: 'DOWN' })); + assert.deepEqual(view.badge, { kind: '', label: 'Not Connected' }); + assert.equal(view.message, 'No server connected.'); +}); + +test('an unreachable client is never reported as a missing server', () => { + for (const state of [reduce(loaded(), 'client', { reachable: false }), reduce(emptyState(), 'client', { reachable: false })]) { + const view = linkView(state); + assert.deepEqual(view.badge, { kind: 'down', label: 'Client unreachable' }); + assert.equal(view.showDetails, false); + assert.ok(!view.message.includes('No server connected')); + } +}); + +const plan = (overrides) => planKnown({ + shown: ['http://a:38471'], + knownServers: ['http://a:38471'], + activeServer: 'http://a:38471', + selected: 'http://a:38471', + focused: false, + switched: false, + ...overrides, +}); + +test('an unchanged list is left alone', () => { + assert.deepEqual(plan({}), { action: 'keep' }); +}); + +test('an empty list shows the placeholder once', () => { + assert.deepEqual(plan({ shown: [], knownServers: [], activeServer: null, selected: '' }), { action: 'render', values: [''], selected: null }); + assert.deepEqual(plan({ shown: [''], knownServers: [], activeServer: null, selected: '' }), { action: 'keep' }); +}); + +test('a changed list keeps the selection the user is on', () => { + const result = plan({ knownServers: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); +}); + +test('a changed list falls back to the active server when the selection vanished', () => { + const result = plan({ shown: ['http://a:38471', 'http://c:38471'], selected: 'http://c:38471' }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471'], selected: 'http://a:38471' }); +}); + +test('a changed list is deferred while the select has focus', () => { + assert.deepEqual(plan({ knownServers: ['http://a:38471', 'http://b:38471'], focused: true }), { action: 'defer' }); + assert.deepEqual(plan({ focused: true }), { action: 'keep' }); +}); + +test('a switch of the active server selects it even with focus or an unchanged list', () => { + const result = plan({ shown: ['http://a:38471', 'http://b:38471'], knownServers: ['http://a:38471', 'http://b:38471'], activeServer: 'http://b:38471', selected: 'http://a:38471', focused: true, switched: true }); + assert.deepEqual(result, { action: 'render', values: ['http://a:38471', 'http://b:38471'], selected: 'http://b:38471' }); +}); + +test('versions are classified by update and check state', () => { + assert.equal(classifyVersion({ updateAvailable: true, checkState: 'OK' }), 'outdated'); + assert.equal(classifyVersion({ checkState: 'NOT_CHECKED' }), 'checking'); + assert.equal(classifyVersion({ checkState: 'OK' }), 'current'); + assert.equal(classifyVersion({ checkState: 'NO_RELEASES' }), 'current'); + assert.equal(classifyVersion({ checkState: 'ERROR' }), 'unknown'); + assert.equal(classifyVersion({ checkState: 'UNAVAILABLE' }), 'unknown'); + assert.equal(classifyVersion(null), 'unknown'); +}); + +test('the versions panel renders from the pushed versions', () => { + const view = versionsView({ + client: { currentVersion: '0.1.0', latestVersion: '0.2.0', updateAvailable: true, checkState: 'OK', releaseUrl: 'https://example.test/r' }, + server: null, + }); + assert.deepEqual(view.client, { kind: 'outdated', label: 'Update available: v0.2.0', version: 'v0.1.0', href: 'https://example.test/r' }); + assert.deepEqual(view.server, { kind: 'unknown', label: 'No server connected', version: '—', href: null }); +}); + +test('only http release links are rendered', () => { + const view = versionsView({ client: { currentVersion: '0.1.0', latestVersion: '0.2.0', updateAvailable: true, checkState: 'OK', releaseUrl: 'javascript:alert(1)' }, server: null }); + assert.equal(view.client.href, null); +}); + +test('versions that were never delivered read as unable to check', () => { + assert.equal(versionsView(null).server.label, 'Unable to check'); + assert.equal(versionsView(null).client.label, 'Unable to check'); +}); + +test('a server that has not answered yet is connecting, not unreachable', () => { + const view = linkView(loaded({ link: 'CONNECTING', running: null, health: null })); + assert.deepEqual(view.badge, { kind: 'checking', label: 'Connecting…' }); + assert.equal(view.showDetails, false); + assert.equal(view.message, 'Connecting to http://a:38471…'); +});