From b25f5e209593ed2bb2793c5fef21c56b7e9f026b Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Sun, 13 Sep 2026 15:38:52 -0500 Subject: [PATCH 1/6] Finish renaming, setup issue templates and testing workflows, add Makefile, cleanup setup process. --- .dockerignore | 4 +- .github/ISSUE_TEMPLATE/bug_report.yml | 59 + .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/feature_request.yml | 39 + .github/workflows/integration-dev.yml | 17 + .github/workflows/integration-main.yml | 16 + .github/workflows/issue_handling.yml | 55 + .github/workflows/pr_handling.yml | 46 + .gitignore | 1 - CHANGELOG | 26 + Dockerfile | 2 +- Makefile | 5 + README.md | 35 +- build.gradle.kts | 1 - docker-compose.example.yml | 9 +- gradle.properties | 3 - gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48966 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew.bat | 186 +-- install-util.sh | 40 - install.sh | 57 - settings.gradle.kts | 9 - .../Configuration.java | 6 +- .../MediaGarrd.java | 0 .../api/ApiExceptionHandler.java | 76 + .../api/ClientController.java | 147 ++ .../mediagarrdclient/api/Endpoints.java | 21 + .../api/ServerConfigController.java | 86 ++ .../dto/BackupDto.java | 0 .../dto/ClientStatusDto.java | 0 .../dto/ConnectionStatusDto.java | 0 .../dto/IntervalUpdateRequest.java | 0 .../dto/PickupProgressDto.java | 0 .../dto/PickupStartDto.java | 0 .../mediagarrdclient/dto/ServerConfigDto.java | 6 + .../dto/ServerSelectionRequest.java | 0 .../dto/ServerStatusDto.java | 0 .../mediagarrdclient/dto/ServiceDto.java | 6 + .../service/BackupPickupService.java | 275 ++++ .../service/ClientStateService.java | 137 ++ .../service/ServerApiService.java | 224 +++ .../service/ServerDiscoveryService.java | 319 ++++ .../mediaguardclient/WebMvcConfig.java | 22 - .../api/ClientController.java | 216 --- .../mediaguardclient/api/Endpoints.java | 28 - .../mediaguardclient/api/WebController.java | 13 - .../service/BackupPickupService.java | 330 ---- .../service/ClientStateService.java | 133 -- .../service/ServerApiService.java | 192 --- .../service/ServerDiscoveryService.java | 293 ---- src/main/resources/application.yml | 12 +- src/main/resources/static/css/mediagarrd.css | 305 ++++ src/main/resources/static/index.html | 1343 +++-------------- src/main/resources/static/js/api.js | 34 + src/main/resources/static/js/backups.js | 206 +++ src/main/resources/static/js/connection.js | 115 ++ src/main/resources/static/js/format.js | 44 + src/main/resources/static/js/main.js | 50 + src/main/resources/static/js/notify.js | 12 + .../resources/static/js/pickup-interval.js | 25 + src/main/resources/static/js/server-config.js | 33 + src/main/resources/static/js/services.js | 96 ++ src/main/resources/static/js/settings.js | 29 + src/main/resources/static/js/views.js | 17 + .../mediagarrdclient/MediaGarrdTest.java | 52 + .../api/ClientControllerTest.java | 170 +++ .../api/ServerConfigControllerTest.java | 139 ++ .../service/BackupPickupServiceTest.java | 199 +++ .../service/ClientStateServiceTest.java | 103 ++ .../service/ServerApiServiceTest.java | 123 ++ .../service/ServerDiscoveryServiceTest.java | 165 ++ .../api/ClientControllerTest.java | 97 -- .../service/ClientStateServiceTest.java | 35 - 73 files changed, 3805 insertions(+), 2747 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/workflows/integration-dev.yml create mode 100644 .github/workflows/integration-main.yml create mode 100644 .github/workflows/issue_handling.yml create mode 100644 .github/workflows/pr_handling.yml create mode 100644 Makefile create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties delete mode 100644 install-util.sh delete mode 100644 install.sh rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/Configuration.java (87%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/MediaGarrd.java (100%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/BackupDto.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/ClientStatusDto.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/ConnectionStatusDto.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/IntervalUpdateRequest.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/PickupProgressDto.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/PickupStartDto.java (100%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/ServerSelectionRequest.java (100%) rename src/main/java/wellatleastitried/{mediaguardclient => mediagarrdclient}/dto/ServerStatusDto.java (100%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/api/WebController.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java delete mode 100644 src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java create mode 100644 src/main/resources/static/css/mediagarrd.css create mode 100644 src/main/resources/static/js/api.js create mode 100644 src/main/resources/static/js/backups.js create mode 100644 src/main/resources/static/js/connection.js create mode 100644 src/main/resources/static/js/format.js create mode 100644 src/main/resources/static/js/main.js create mode 100644 src/main/resources/static/js/notify.js create mode 100644 src/main/resources/static/js/pickup-interval.js create mode 100644 src/main/resources/static/js/server-config.js create mode 100644 src/main/resources/static/js/services.js create mode 100644 src/main/resources/static/js/settings.js create mode 100644 src/main/resources/static/js/views.js create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java delete mode 100644 src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java delete mode 100644 src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java diff --git a/.dockerignore b/.dockerignore index c843ac6..dbeb426 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,7 +14,5 @@ secrets .gitignore LICENSE README.md -install-util.sh -install.sh CHANGELOG -docker-compose.yml.example +docker-compose.example.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..79f75b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,59 @@ +name: Bug report +description: Create a report to help us improve +title: "[BUG]: " +labels: ['Type: Bug', 'Status: Needs Triage'] +body: + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + attributes: + label: To Reproduce + description: | + Steps to reproduce the behavior: + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. + validations: + required: false + - type: input + attributes: + label: OS + description: e.g. Linux + validations: + required: false + - type: input + attributes: + label: Version + description: e.g. 22 + validations: + required: false + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..7e6c25b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,39 @@ +name: Feature Request +description: Suggest an idea for this project +title: "[FEAT]: " +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/workflows/integration-dev.yml b/.github/workflows/integration-dev.yml new file mode 100644 index 0000000..80c6dd4 --- /dev/null +++ b/.github/workflows/integration-dev.yml @@ -0,0 +1,17 @@ +name: Integration Test Dev Branch with Server + +on: + push: + branches: + - dev + pull_request: + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: dev + client-branch: ${{ github.head_ref || github.ref_name }} diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml new file mode 100644 index 0000000..bd5d151 --- /dev/null +++ b/.github/workflows/integration-main.yml @@ -0,0 +1,16 @@ +name: Integration Test Main Branch with Server + +on: + push: + branches: + - main + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: main + client-branch: main diff --git a/.github/workflows/issue_handling.yml b/.github/workflows/issue_handling.yml new file mode 100644 index 0000000..a9f75ca --- /dev/null +++ b/.github/workflows/issue_handling.yml @@ -0,0 +1,55 @@ +name: Handle duplicate status label + +on: + issues: + types: [labeled, unlabeled] + +jobs: + correct-status-labels: + runs-on: ubuntu-latest + steps: + - name: Ensure one Status label per issue + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.MEDIAGARRD_CLIENT_ACTIONS_TOKEN }} + script: | + const issueNumber = context.payload.issue.number; + const statusLabelsToCheck = [ + "Status: Needs Triage", + "Status: Approved", + "Status: Waiting on Child Issues", + "Status: Waiting on Server Update" + ]; + + const existingLabels = context.payload.issue.labels.map(label => label.name); + const existingStatusLabels = existingLabels.filter(label => statusLabelsToCheck.includes(label)); + const addedLabel = context.payload.action === "labeled" ? context.payload.label.name : null; + + let keep = null; + if (statusLabelsToCheck.includes(addedLabel)) { + keep = addedLabel; + } else if (existingStatusLabels.length == 1) { + keep = existingStatusLabels[0]; + } + + for (const label of existingStatusLabels.filter(label => label !== keep)) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label + }); + console.log(`Removed label "${label}" from issue #${issueNumber}`); + } + + if (keep) { + console.log(`Status label: "${keep}" is set correctly`); + } else { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: ["Status: Needs Triage"] + }); + } + diff --git a/.github/workflows/pr_handling.yml b/.github/workflows/pr_handling.yml new file mode 100644 index 0000000..fe9016a --- /dev/null +++ b/.github/workflows/pr_handling.yml @@ -0,0 +1,46 @@ +name: Require approved issue + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + require-approved-issue: + if: github.head_ref != 'dev' + runs-on: ubuntu-latest + permissions: + issues: read + pull-requests: read + steps: + - name: Ensure every linked issue is approved + uses: actions/github-script@v7 + with: + script: | + const { repository } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 25) { + nodes { number labels(first: 25) { nodes { name } } } + } + } + } + }`, { + owner: context.repo.owner, + repo: context.repo.repo, + number: context.payload.pull_request.number + }); + + const issues = repository.pullRequest.closingIssuesReferences.nodes; + if (issues.length === 0) { + core.setFailed("Link the approved issue this pull request resolves, e.g. \"Closes #12\" in the description"); + return; + } + + const unapproved = issues.filter(issue => !issue.labels.nodes.some(label => label.name === "Status: Approved")); + if (unapproved.length > 0) { + core.setFailed(`Linked issues without "Status: Approved": ${unapproved.map(issue => `#${issue.number}`).join(", ")}`); + return; + } + + console.log(`All linked issues are approved: ${issues.map(issue => `#${issue.number}`).join(", ")}`); diff --git a/.gitignore b/.gitignore index 6703b86..6feddf8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .gradle .settings/ build -gradle/ **/.settings/ **/.project **/.classpath diff --git a/CHANGELOG b/CHANGELOG index e69de29..d586cdb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -0,0 +1,26 @@ +# CHANGELOG + +## 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 diff --git a/Dockerfile b/Dockerfile index b6aca51..3be39cf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all FROM eclipse-temurin:21-jre WORKDIR /app diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9fee8ce --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +.PHONY: test + +test: + ./gradlew test --warning-mode all + diff --git a/README.md b/README.md index 0101992..35e5bed 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,46 @@ This is the official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +## Requirements +- Docker with Compose v2 (`docker compose ...`) +- A running [MediaGarrd Server](https://github.com/MediaGarrd/Server) that has finished its first-time setup + ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Client.git cd Client -./install.sh # Drops .env, client.env, and docker-compose.yml +cp docker-compose.example.yml docker-compose.yml +docker compose up --build -d +``` + +Then open `http://:8081`. + +The defaults in `docker-compose.yml` work as-is. To change them before the first start: +- **Port:** change both `CLIENT_PORT` and the `ports` mapping (default `8081`). +- **Where downloaded backups are stored on the host:** change the left side of the `./data/client/downloads` volume. +- **Where the client keeps its state on the host:** change the left side of the `./data/client/state` volume. This holds the selected server, known servers, and pickup interval, so keep it on persistent storage. +- **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_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. + +Every setting is stored in the `./data/client/state` volume and survives restarts and container rebuilds. + +### Finding servers +"Scan Local Network" checks every address of the networks the client is attached to, on `MEDIAGARRD_SERVER_PORT`, `38471`, `8080`, and `80`, and lists every MediaGarrd server that answers. "Connect by IP" also accepts `:`, and scans every port of the host when the server is not on one of those ports. + +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. + +## Updating +```bash +git pull docker compose up --build -d ``` +Downloaded backups and the client state live in the mounted `./data/client` volumes and are kept. ## License [GPLv3](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index 60673ae..1c249cd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,7 +5,6 @@ plugins { } repositories { - // Use Maven Central for resolving dependencies. mavenCentral() } diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9ad9bfb..4c12fe2 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -2,18 +2,15 @@ services: mediagarrd-client: build: context: . - dockerfile: ./Dockerfile + dockerfile: Dockerfile container_name: mediagarrd-client environment: - CLIENT_PORT=8081 - - CLIENT_PICKUP_INTERVAL=PT1H - - CLIENT_DOWNLOAD_DIRECTORY=/var/lib/mediagarrd/downloads - - CLIENT_STATE_FILE=/var/lib/mediagarrd/client/state.json + - CLIENT_PICKUP_INTERVAL=PT12H - MEDIAGARRD_SERVER_PORT=38471 - - MEDIAGARRD_SERVER_IP=192.168.50.55 ports: - "8081:8081" volumes: - "./data/client/downloads:/var/lib/mediagarrd/downloads" - - "./data/client:/var/lib/mediagarrd/client" + - "./data/client/state:/var/lib/mediagarrd/client" restart: unless-stopped diff --git a/gradle.properties b/gradle.properties index 377538c..1385fa5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,2 @@ -# This file was generated by the Gradle 'init' task. -# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties - org.gradle.configuration-cache=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..d997cfc60f4cff0e7451d19d49a82fa986695d07 GIT binary patch literal 48966 zcma&NW0WmQwk%w>ZQHhO+qUi6W!pA(xoVef+k2O7+pkXd9rt^$@9p#T8Y9=Q^(R-x zjL3*NQ$ZRS1O)&B0s;U4fbe_$e;)(@NB~(;6+v1_IWc+}NnuerWl>cXPyoQcezKvZ z?Yzc@<~LK@Yhh-7jwvSDadFw~t7KfJ%AUfU*p0wc+3m9#p=Zo4`H`aA_wBL6 z9Q`7!;Ok~8YhZ^Vt#N97bt5aZ#mQc8r~hs3;R?H6V4(!oxSADTK|DR2PL6SQ3v6jM<>eLMh9 zAsd(APyxHNFK|G4hA_zi+YV?J+3K_*DIrdla>calRjaE)4(?YnX+AMqEM!Y|ED{^2 zI5gZ%nG-1qAVtl==8o0&F1N+aPj`Oo99RfDNP#ZHw}}UKV)zw6yy%~8Se#sKr;3?g zJGOkV2luy~HgMlEJB+L<_$@9sUXM7@bI)>-K!}JQUCUwuMdq@68q*dV+{L#Vc?r<( z?Wf1HbqxnI6=(Aw!Vv*Z1H_SoPtQTiy^bDVD8L=rRZ`IoIh@}a`!hY>VN&316I#k} z1Sg~_3ApcIFaoZ+d}>rz0Z8DL*zGq%zU1vF1z1D^YDnQrG3^QourmO6;_SrGg3?qWd9R1GMnKV>0++L*NTt>aF2*kcZ;WaudfBhTaqikS(+iNzDggUqvhh?g ziJCF8kA+V@7zi30n=b(3>X0X^lcCCKT(CI)fz-wfOA1P()V)1OciPu4b_B5ORPq&l zchP6l3u9{2on%uTwo>b-v0sIrRwPOzG;Wcq8mstd&?Pgb9rRqF#Yol1d|Q6 z7O20!+zXL(B%tC}@3QOs&T8B=I*k{!Y74nv#{M<0_g4BCf1)-f)6~`;(P-= zPqqH2%j0LDX2k5|_)zavpD{L1BW?<+s$>F&1VNb3T+gu!Dgd{W+na9(yV`M7UaCBuJZg1Y)y6{U}0=LTvxBDApz@r>dGt(m^v|jy&aLA zdsOeJcquuj3G^NkH)g)z@gTzgpr!zpE$0>$aT^{((&VA>+(nQB!M(NnPvEP}ZRz+6 zE!=UW!r7sbX3>{1{XW1?hSDNsur6cNeYxE{$bFwZzZ597{pDqjr%ag85sIns_Xz%= zqY{h#z8J6GA~vfLQ2-jWWcloE5LA62jta=C*1KxAL}jugoPqj4el4R4g3zC4nE#2-NeS{c3#!2tIS|1h8*|kpw2VSH9OcIQZx0Yh!8~P&p}fI$4Bj9Z zr5Yv?i-PfO#<}clM>mO(D0wHniZZdv8pOuJFW z+-u}BH84PQCgT~VWBM88vtCly1y$uEGJ<7vnW%!2yV>l>dxA0X0q{cN6y3u$8R-*f z-4^OlZ1HmxCv`dFW%quP<7xzAbtiFxvY0M1&2ng&A}QXAVR=prc_5m(D+_?hv#$M^ zG#MQ#fHMc!+S%HgU^Qv7Z9eu6eNqpSr3e8(;No*YfovbJ;60LjCzv9O~^>gFKO>t zGZg9`a5;$hksp*fHp{7&RE@DM&Pa@a>Kwk%*F7UGO|}^Z0ho1U$THOgX9jtCW6N$v zLOm}xcMBtw)CC(;LLX!R9jp|UsBWGfs@HaMiosA3#hFee7(4vLY}IrhD++}>pY zo+=_h+uJ;j^CP*OGQ9$0q+%}UB`4`5c766d#)*Czs<91wxw)jI^IdvyjT%<8OqI=i zNn0OUqW#POg^4ma)e2b?*Xv;dri*N0SJ7_{&0>;S!)!YV1TQuiT1C3ZFDvThe}yTCmErx#6yyQ4X@OAbHhdEV!K2%;7J>tiUZF)>Z|eRVDwtDC~=J z*M8|WEgzsyNH@-5lJE+P6HrurgY!PqtWk z^69SOHZ*}xn|j2FDVg`qRT}ob*1XiGo=x8MDEX)duljcVO}oJjuAbB$Z+f&!{z3k< zO6+{@O#2^s4qT`6k}Nw?DKV1DU~}0jVA)(kNz$c-p`*FNG#Gb&o?ko70F||R^y*hD z6HD|hJzF)G&^K=vuN$@b2fIfHVFw@hC_-0hPnB!1{=Nn~ran4VeTMM(Xx2A3h95U} z&J#Kw4>*V(LHOA<3Dy{sbW-9k5M2<%yDw~ce0+aez8 z04skG8@QEESIL;m-@Mf_hY!)KkEUowHu(>)Inz(pM`@pkxz z1_K#Qs6$E^c$7w=JLy>nSY)>aY;x2z`LW-$$rnY0!suTZSG)^0ZMeT#$0_oER zfZ1Hf>#TP|;J^rzn3V^2)Dy!goj6roAho>c=?28yjzQ>N-yU)XduKq8Lb3+ZA|#-{ z?34)Ml8%)3F1}oF;q9XFxoM}Zn{~2>kr%X_=WMen%b>n))hx6kHWNoKUBAz?($h(m(l;U*Gq7;p5J{B;kfO^C%C9HhtW!=O3-h>$U zI2=uaEymeK^h#QuB8a?1Qr0Gn;ZZ@;otg2l>gf= z$_mO!iis+#(8-GZw`ZiCnt}>qKmghHCb)`6U!8qS*DhBANfGj|U2C->7>*Bqe5h<% zF+9uy>$;#cZB>?Wdz3mqi2Y>+6-#!Dd56@$WF{_^P2?6kNNfaw!r74>MZUNkFAt*H zvS@2hNmT%xnXp}_1gixv9!5#YI3ftgFXG20Vt1IQ(~+HmryrZI+r0(y2Scl+y=G^* zxt$Vvn&S=Vul-rgOlYNio7%ST_3!t`_`N@SCv$ppCqok(Q+i_?OL}2@TU$dr6B$c8 zQ$Z(lS6fp%7f}ymQwJAIdpkN~8$)O3|K7Z;{FD?hBSP-#pJgq0C_SFT;^sBc#da0M z;^UuXXq{!hEwQpp(o9+)jPM6ru1P$u0evVO(NJ;%0FgmMNlJ+BJ zf^`a|U*ab?uN*Ue>tHJ$Pl~chCwRnxi3%X06NxwlIAKa*KReLL^y1B^nuy|^SPj3} z5X|?1divh3@zci;648jb2qEOm!_8Tjh3gi;H%2`d`~Q(IL{Wcl1C18+&P>tU&0!nO z&+7mpvr2SsTj=@sX zxG=;T^f7Rg=c=V*u8X(fo)4;RYax^+=quviOJ{>r6{wgf)g){I&qe`=HL}6J>i6Ne zSZ*h9f&JG>Y`@Bg5Pb&>4&UqFp9I<8o`n4W_V=4AugM`RqUeS-!`OyNLyKMqa_Ct| zON-hyk#-}{lZZx>B1F@dF^8S>x|C*QAjKqn&Ej9H#z@Q#KA*ckBX@^;gIP&?aK15l z*EY@kG57oUcm(d{NyXg6$Kj#xR5XdZ1EBCT+Zy!gyXwN&b_zI&$$>7R#{ zh8U@H8NY-cA*CBfH$OCs^priPwtwrzFjDO}DBn#mgbI~hn}cp2U{yv@S)iy|jR9+E zgd(hF|1cyC#te0P;iFGqpNBqc(k<{p^1>wHE_c8Tr4|&NV4mzpzFe;Cr)C~qpVNjl z^u(^s5=kj{QBae)Y*#^A39jT4`!NuIUQzD#DOyfa!R=PrX6oS@x@kJV)Cn$!xTK9A&VI#F-Slt8I4|=$bcjaC5h=9E{51g8X5q1Qfg~~G>qAgy*7h4-WuqE zlIEx?Hu*%99?$6TheLAD4NIMO=Q@*;gaXDl6yLLXfFX0*1-9KQm42c%WX*AXFo$it z?FwnWn2tBHY&Qj6=PV?ergU$VKzu+`(5pCRqX}IoSFo?P!`sff%u1?N+(KsoL+K={ zi*JGl%_jiuB;&YW+n%1o^%5@!HB9}OlIdQZ*XzQ%vu!8p2gnKW+!X>@oC{gp3lNx^ z82|5Jdg9-B<1j|y(@3J;$D-lqdnf0Q6T~q7;#O}EMPV3k(bi$DpZwj9(UhU%_l&nN zR}8tN_NhDMhs)gtG*76~+W2yQ{!kDTE@X4gft2?W;S$BLp9X z;sh2jpm!mkfPX>Vuqxyt76<@f4fyY%&iuDfS1@#PHgzHqG;=X^`X}t2|Alr^lx^ja z1rhvG(PH(a0THitc?4hk=P*#IS;-`fjOKqJ4kgo@dAD@ob*))H)=)6s3cthp&4Q55 z4dQRdG0EveK*(ZUCFcCjILgS#$@%y=8leYxN-%zQaky@H?kjhyBrLYA!cv>kV5;i1 zZ^w&U7s&K8fNr4Pfy9GyTK2Tiay4Y_PsPWoWW5YA8nfUkoyjU)i@nKj@4rY13sxO6 z_NzYdG=Vr<@08Xi#8rnX&^d{Bl`oHXO6Y3!v2U~ZV>I*30X3X&4@zqqVO~RyF)6?a zD(<+33_9TqeHL)#Y?($m4_zZvaJXWXppZ4?wo?$wF)%M6rEVk2gM=l9k+=*Q+((fI zIUBH6)}M?ahSxD4lgmJ30ygk#4d!O@?%WNEONommx`ZK81ZV)mJpKB`PgQ}F>NGdV zkV|>^}oWQd6@Ay7$&)6!% zOu_p~TZ3A#G_UqiJ85&*$!(+!V*+*{&-JXb53gtc9n3>8)T$jUVXe+M6n$m633Mi? zlh5{_+6iZ<%gMWMrtHyDl(u-hMl^DViUDc50UD;0g_l$F`Hb(F=o+?94B0fjb;|?Q5c~TWX>t8i1RP@>Ccgm z?2=z0coeb?uvn44moKFb^+(#pAdHE7{EW(DxJE=@Z0^Am`dpm98e`*S+-~*zmhdQ7 zCNig0!yUu5U#>KKocrg-xMjQoNzQ`th0f{!0`ammp_KMFh?_zF4#YhF35bPE&Fq~_ z#VnniU6fso{!3Z^1C57q?0i!ok(a zL;-f$YlDk%qi%n637_$=Gw=bBY}8#meS~+#X}Oz~ZKd%q(UE>f%!qca?(u}) z!tLTuQadlAN;a#^A?!@V=T?oeJ1f7yRy)H1zn_+wARewYIYr`zD=^v+D|ObvH4rOB zT@duqF>$Dk6&i|pZh?%Wq-7_kyP4l)-nqBz#G0lqo3J2D%zmbU)>3)5e?sTZy8|~B zPC7!`eD+deR?L6$6 z-e{!ihef=f<4HPZ9rSt&yb=5Q)BFAXWPR^~a&Zru?8146wvlm;<)ugbd|!}O6aE0t z6`#KqcH#S#*yz-K90+!Fhv+ zKH+?!_0yl|gWXSaASLcB9a8g7i%qz*vbO)YW`Q@Nxpp*6TZ*OO8Z|5-UWihd@CUXF zY!aTAZ$c^?4hiaq34=s2il}#Pxu=#c2^=(PbHNAyUqy__kR+n?twKrQe^8l6rk=orf}Mk80viC1NZ^1q zeF~g*iGp0=jKncK%s@#jZcn6=EiR<8S#)yiEOuwbG;SV$4lB^R?7sxOf8)oq$sT)) zA&nBCFJxsnci+)owdCHV#cjP2|1j22xIRsxHrLLBk3GI|OppUv3%r>#;J|26!W>xC z9gq@NQWJ`|gH}F{-QG#R6xlT<;=43amaDT>VaG*;GfPZJ&W*rO8WAQQc^JGw-fz-| zzAe&RAnC(gAP#FoJtt~ynR3Z<)m_<9Oo)XW}CWd50^eI4!1p4}s(zLhBIDi5r zr{UH>YIz2!+&Cy(RI(;ja_>SUC2Q`ohWPlI+sK-6IU}*nIsT)vLnuVPFM%~gdel}S zUlY%>H$?-rQRGTdUM^p^FEkqnwC{^BGl|gM)h9zkXplL90;yOcgt(8&LJwOj!5Qgy zu$@^*k%9JoAzwj@iSB^SNu#YVl@&*g$uYxxsJBvIQ>bfuS97JccQcS7&a z)`1m2^@5c9pD`P$VqH*O*fxkvFRtH-@Pd0@3y2!jW>i=jabBCJ+bW@wwUkWjwx_WR zHH5*XR4hbQ1`D@4@unmyEX)!?^~_}~JQNvP4jO&F)CH9srkFhf8h*=P z;X1&vs_&v03#BGc`|#@!ZONxVj9Ssb#_d63jxA6dX_RBt(s;ig3#s(YU3P3klF;mc z%%@^IJUAlGE=cnsTH+(qb1SxN@HzfAjYcUCb(VU)JV^3ZC;#k!t?XjaC!|68eLE zU_hlvOSNj7Qlr{x)y$S$l^2DPCMA=pzapcSkjfk*r!iWU%T{?<3#Hw6s1ux1^Ao6o zR@5DIfo-|c9AaFw848Y!BVG-+vURe;I29F#hLu$9o}oSa9&2sgG#;lj@@)9|2Z3 zon?%NV&AYSVnd~eW~v0yoF$X^1FR@i2kin0mFLG8-aA>hYK;B%TJ~7%P4?_{Bu<0t zvmI)Uk-MRncVb)A890>OqnYf=wu-J5A~^%4jpK~*xp)=h0BZB4*5uWrP>iRV+|kMX zv+BEskY~(P-K)-!JSHR`$brY)HFI|L@YyrxheT3cgHu}KtF%s%k3B`X)E_lA=E>M4 z2VV3M{c0*)`qZAsJ==)F#D~2Ndzm@hKhSBL_Sf3{ctckh-rB`gkfC?Dp6FdM?p;vv z#UlQMp3H5*)8o#Ys@-aj7O#brUfgQ7BjG`7 ztoE7v-tH2%KVC$xKYf%uvZD!_uf3x>h?8r!zYHkcc7$Gdn(6cDmYL&p3pCfaSfY4$ zG|yuujr6!Wl0}V%* zQ;nY##kEdvo8YY=SVDb)M>^Ub9e#4c$O&urD$uaRtxm-UH=6_s0m^^5y^_+F^Q?;8 z+Fd?+De}er^2EmFNn&e8SyS*`*`e;KFIG&+x5iWCsrEyH*0SFBCMx?`m5~hl1BrT> zr8W3*3}Fwsx@%UOuxNoCSoL%AM{Uj|v@>l{pYYI&D$j`&**;?X`cuOOk~?;U{~xvDUjaiH^d`A+gQL#Z?*lm)x_n6R-S% zf6*=Q1m>mq5|Niefl8s=5F={ncn5S;6~&Ns2)yGZ@wt&u4c+)Sk?hdfI^b77@K-=y zM_k=j5hp&u`2nkJK+2Lw`uLypr4dO?Bm3BTZdtWnQa5unCoTKIiG81t4bG`epBU5| zG{toT`)LE}&j{P+AFj`YZrjF-^>k+`zCM`QcQz^Ba4BEte@S}j=Q_Opx14jq|DB}& zNB44BOJ`?GJM({v`gh9pzbg8-%Un=E@uLfJwGkagLEM^!`ct3s5@-xqq*xd+2C@eu z*1ge`retZK)=bPO<`>@62cLN?^S%v#EsiPQF`cg&I7{}l?)}O$!^wNJp4Zd;1yBbQ zv@_7x7d6aXJvGHkNNcOg?A};m_Nq7H=(+zqf9)e3&yP^EU63Ew!NW4CYj_!=OTVb* z-ijSrv0M)u=MF=@+`3ldT-hzOn$Ng><)WL0vqQ&jH>W7EmLLQY+c?%i9~f_x&{OYX z{?kyyNZ&gT*m$(%-OeDAJeC^c)X!k${D*c;c}9)0_7iWMbfu)!j3+{*!Dj|?C`sGz z2xWha)#`9@p*{-X2MN2a;%FM-WqB2h)GTqQH$ZsGD#Wi`;+$i?fk;23fLpYI^3TT3 z5+Zn3cu-_2Ck*@%3^L3}JpVN`5ZJ;gmKn>gm(Z)b%!v|RYf(qrmGL#0$WHQFw4mJqQ85w=$tn^7(z|eJ$3R0} z2k9^EU<^-$ygq!ZR+7wT0KViK8qkAO7xs*e@1dq{=M3haulHwA0~BYNytr7k2K*(W z755P9a^;Hdl2X;K{c}yWr|QH?PEuh6x)9n{^3m2QUfC_Q*BW&<9#^ZVwOolx@6y9- z-YF=S;mEypj68yxNxfJ56x%ES`z-5$M${V1HX(@#R>%$X`67*Ab8vC6UzvoDOY*P= zFbPXany0%>rqH1gi7d>e`=PWZTG>^=#PQf&iJjJ0&2dO(4b8) zCl%8xJg1mg4__!?t|y_roExn~%u@Eu|p9YFb`8_qP@v#KW#kFs4eVetJ+Q+s|Y0?#D z@?dt_BA7C4tGpjOB~*LFu0!5oU(_xj7xA$meN)Z;q4Z_Rb7jY1rJBzJPr0V=(y99F zh=V-NbK+64rd#ltw~7X-%kP$R896DxRuj)p7Zj@8&>IlP&}ME3s9eV2R>SpUnSxeg zmpm?HQJ^u1T;pvwvlc4F_)>3P~jlTch4+u6;o{@PtpnJcn~p0v_6Po%*KkTXV#2AGc) zv)jvvC?l#s$yvyy=>=7D3pkmV24xhd7<5}f_u5!8gmOU|4555dv`I=rLWW!W!Uxg| zFGXpH3~)9!C2|Y6oB~$gz(;$CTnw&R&psa+E!KNgrE1+WkLM6SOf$>sGW+Y{>u?Fw zTc!xG{pa3c#y@d$d0e7a9~e_xjGcaw5f6Fk>lg$Jm}cFd%BO_YT(9s+_Q;ft%1*k$ z_cXkf&QHkaQr9U?*Gr$r6|bCV>2S)Cedfk3rO?JbyabY zgqxm#BM7Sg6s-`5%(p@SxBJzR6w`O6`+Kuo36wwBzwf6K{0HENVz^^w|E$r zdZM%T0oy8OK|>>2vSzw5rqoqEroCZ%(^OmOSFN84B2-8Z?R1)Pn9|5Xkui(fQRl^zA35EH^(JbuQd@Uh z2FJ6C(5FDD(++_NLOG)1H<+X~pt68d@JiB8iUQSZ+?qc;Jr+aJ8bKF3z`K&zSl&C7 zEgl&!h?sc=}K7 ziEC(3IrY?h7|d= zVjh{@BGW^AaNcdRceoiKmQI+F$ITdcM$YigXtH)6<-7d@5DyyWw}s!`72j`A{QC~e ze-u0a6A;QSPT$vqf3f(kO1j^%GYap*vfWQ@X=n{lR9%HX^R~t+HoeaT5%L7XSTNn` zCzo})tF@DMZ$|t6$KTx+WQqu~PXPa9FL&shBGx3C>FlGz}7gjfv}(NKvjR#r5PL$a1>%asaylWA8^g!KJ=$}_UccHmi zAZd5c{I&Ywpi3a1#27C6TC~zm3y8D>_1an8XHGNgL?uT$p+a<5AdWLR6w9jdhUt9U zz?)93=1p$x;Qiq!CYbX&S}+IITWLkfu%T6X5(pk9-fs8lh9z8h?9+>GlFeFcs*Z>u zJSaL!2?L8LbOu_Ye!=4~ZKL?643lcsNn8>qUT|q&Rv+(z>Z9=tyG&5}zZK&Q?S!nG zR;Ui^<406=jLYA>zl!a-OXH#J-pP4A`=)r%9HV5m1qGZ1m*t^wi>3$JRcH)3Q(LQz z(3}~y3=QsUu!PN$$N~#yBP@=aJ+Bkp_hx8^x1Ou6+(Kk9l1CXr4p~IQvq@AUePuAj zcq5>YDr(JTmrAuLwn6sgohTR-vc^y^#I{grF7 zg}8?&5!^$|{X`C;YrZ7?rKH#`=n0zck(q37+5%U;Hmds2w+dLmm9|@`HqQ<5CUEz{I1eNIL?X~rd{f71y z>_<94#1G+j`d5|fKK@>QDK6|HRR|9UZvO6HdB1afJvuwUf8bw>_Fha)Ii8I}Gqw}p zdS~e^K4j{d%y+A#OBa1C4i0)sM=}tjd8fZ9#uY}{#G7rJp{t6?*5*A^KKhim06i{}OJ%eA@M~zIfA`h_gJ_o%w;FaFQMnVkBT|_ z(`m9r+11~EPh9f7>S=$F7|ibj=4Pt>WVzk6NfGRvI_aG66RHig-(S%WKRLP%_h0He``xT))N^RI@6!ADl=*vsqVb|7 zr~Lwl6qn|u!%is<{YA`Mde2Z${@EAHC^t>4`X;F9za=RC{{$4OcGmw%9+{$i@!cCn z;7w~r8HY->M@3OzYh+L7Z2Lc8AcP*FZbl6VVN*_sp}K zQP|=g@aFthq}*?|+Gm4@wbs_?Fx-HD2%)_UDJ);X88~7ch~d0cJ!<7;mv>iv!RS$a z;(-cYTW=K=|F0gIg3EW0%u2CSr(Kx}yLoki|KSIt$#P(O!=UjBGRzb3L3-?NGr7!! z^VC7_Q(GhT;C*(bLivfhlRDVdz7=h%ABuLA2g$qy)A}U@Kj_L-Jd|--fy#-*ESRo| zgu?*?jGEgs9y>1`t}|^Ucd1I=1N=mOo{8Ph zwZS(F%G?nfI{#%sGayNItK9J5P)Qk+^4$ZoXZJ0G1}hwcckJ0g-QJ<)3%`bF8}(ahYIjKFYMtg3X;e7J18ZvDkV@N=nxvDl zo?}lXoT3pZY;4$QKI`~GFuQKv;G6b<8;o89Hd2yu+|%sU(9C=h8ibwZ zARqZ#lk@kp4*#URe-YmpRc&=-b&QP>5b{9{(tH*)(@ZPKfOslBgwCPx6d*{XMX|Q{y0F!5a^ScCE;h8bQmTJR3*}A>aGcDF0?tU)Tnml z#DgruwAva-fiU3s*POY_ZHiJyW%v+733X`&ocwHz$uqJCOhrM;#u*V2eK$D5HiN(` zII{BEg(PV6#_Nv3rZBUyd+TI!>L72KW_Oml6L=pNv#aOl( zgpYxAH^@2aJQu3urlrCeanwSpHHD_Cxb+=cm49{ZU5Z@;{^{okEJ6&fpDD31w~$`% zcz@_REsC~Vq>3YF7yJ41ZEPBW&%|OwlnfG|QNpiX;fGR0f^3?PEf|-33P&LFGe`8^ zaX3M+*h+?6;s|=$j*d|S-r6PSHnmLqm9oshPNpGzlxV21cFrxcQLidd2%h>n%Mc4{ z|JWBvtbb;(-nhWpPO95hR>(e(H$n%*pCh0k4xE#I%xu=#B)zXSaH+azwCI;0@bY<*-10-Qyaq%5NxSlq_@YJUUwy z*d;qPjW^cuKxdXiOWwP}5FN6SZW~NqB%4?|WifPNZr&XNVkzF0n#Y)pbaEodqNO4F z2Bq#^Gr^Ji3!T9`_!D;a1lW$?!LQ-iYV_A{FQ~^C-Jp`_5uOC)6+mzBr4Nl3fHly% zcXeU3x-?#J`=p$6c~$T~V^!C0Bk_3#WYrtoFCx9_5quCQ*4*?XG0n_9%l_!n`M85^ z7}~Clj~ocls6)V&sWGs?B<`{Ob>vnbXZwdda%ipwbzOJ(V`W>KBF5zdCTE8;mc&xU z^clCzd0(T#8*(})tSYSNP1N{FnNVAU^M1S_pq4VEQ*#5nv`CoYSALMEB zf6egyuRMzK2?r^M0hCD*sU;On6c0^Vh|#tRG*n1p5R)QyVw%Va37nMSV%9&uq^hp| zCHeu}y{m=NsA=naDy;q`fd9t)I$Qd-A1Il$#0KyDc>X)hKJViqNB{HnQyf5D(ZJ*J z{-oGB-%Q|QZ%Pqu34>fCy)Asi}IY7luNR9ebgH4DAjCVvSWfa%PE16 zkC7EIuEK}?IR!jgP%eX%dcxk4%N!zIjW4wYMfIq@s%GetDs^g!^p}DH46EP`Nh_wD z4Rwc4ezh1U$Mc)Fe6ii6eD^*iB2MFp-B-HhGTR0tC2?bq$#^J!v1r+Z0y+& znVub*k=*^0yP(c#mEvX}@Abx%&}!W(1olcWEHAVgskbBrzx(f2v&}4~WkVN?af#yi z4IE-(_^)?4e3(d{F@0<~NV5|e0eaB!?(g%l&Hq$UqzC_Enuest?CL+IrSD`tv8|{C z=79vnL=P6ne+}6X1&cd$kam=jCcv`~^y#R{doTh?6D?H)^M7-P+=D@?H;bt$*V+)K z?+?Ex3Z@8JE3c4eHDYItB^tSot;@2p_fuZ8mW^i^a(L;Xn6K+1GuG0n$v(38;+<78 zC?eMzbQCW2%&;U>j}b>YEH5>RkP44$QlG6k(KwXtq{e#13wnx5Jh=uH?lQIl8%Qxr zq%pDC)mYYKa?N>%aF%YwA}CzV@IOV9&a81d9eiU-6F&lGvz68~%{&4LuwV_5{#km3(tf`fejjs%`{Y`|0p!6|-U z8XQA9Sl=*kM|(2KA!LWOCY3Qq4sZ7r&}__rR*Sj(9W8R1_RxI&4TI+_7RSJF&-363 zJvczH?1(`Jb+RDJL9$Whnj8qJRI+Mz9=Qjvubb=Lz8nWVXG{Te;$%s9-D#$)-!{~w zIM(vkr#OM>2F7W$$Lq%fEYl%e|Tsc>9rB9c8 zQoi4nXomx3&sBI9AwaHkoOp%SMDf2@T#73Bi?|!r!Q?wc(^b_u4ranezYx~=aRV-a zD|_WPK^iJh&=)~h{t<>_$VMXsee;{r-|`#H|1?DZgWvuc*!&C2*(yv(4G5s{8ZRzt zZMC~5gjiU@6fPGMN%X~pL};Q`|IfPfs0m9;RV}xSxjb)*gmvGO1`CQb~W1M1{KwXBLyPz0JQG=JkVX zlPq&zNZS59gf-?*5Z0IFitTX4T$1Oo#_~V%4q2vI?Y@UkSHh}H9xZ1va}^oBrCY{+ z3wwj*FHCsS2}GdSG7W(|k+MWu9h1Qs6cft~RH)n*!;)5HmPX1DqrJ3-Cs%i4q^{$N zC&skM7#8f{&S!9Eq-WqyY$u?uTgrSDt#NU%{3bQZtUSkUof4`Z1P8aLOKJ+^dKh%n zfEfQ zO|P*J>;{=`9@D)qpnt`#NH>}sir*&oFC+W!HR)ecHcPwjF-|)}8+tR#@A+~CLl+Ab zCqp+=Cuc(&VGC1ZYg4CxIXYL>33p^wjIWJSh6R=oq)jD52q3~KVGt=w_z(arS!gx^ zSd|?!rzDu1$>0o0Y0+!iZU=ew^Hr+cq(I(C>9}^sBc++0+S#I;js@_NLD9>MH(tN3 zE5F+J_bYdPfYm5%7-e=lm?!-xlvX~nDkBqu!Zf0ra65JD&@tYDW+c@P3W-YyWe4^6 zhW?FUJ;c{^?b`N)03>!@#JI)r2&!6An27q?*^wyUx3T4uyeIl4*(4CV5OTK#RSnYt zq<+RKCdrYIJtdmNC-NtfH)K&pytbM^Mi6JWjkzJo0TdX>HOjJaIQmQ?Q;l2)8oN@d zVyT=%y@TihQaJX7#B2wY#_ufuaF55-sWO{OwUx$2zRyW$YM(CFBs4Y;YmBk(4u&u- zEf@rIR~4#}IMeq$?T%z3s3RAR7m%M?8No;a=1HXKP?ia#uwy!`4v0GFSjZiMii@ib z#xRmA-v~CSVl8z9cEWVEk;9_BKPS6Y2|bk#PAb|}gPxHs-dt*k`5tU#FZL)FLodY8 zmb!m`DagEJ#q1VKwO~%zmw7;LESf5u!KJNm829pbY_w$P2}16`Bb?0uoL3~V71;_U z`B~wKOB7Bp!Vn!M@o?RHydmah!dHPaT`&idV83kQPxA>E=~YgJC<)rdM1#B$JIgnq z0V{p|Cm3eeMaO58Wrv^9-kAOJ+*HR!;;A9z&>78VsYmF9$U^*ZE=K%d7=MZ~G?~Hz zSHlKWK!Us^%?uE6`E|_XI+nC354jkbUPvedHbh(DkKGkquYf}=-EEB1g>RC{O9ORL371y8V*CR5EW z@lmFq%MWEBdeHR7%(Rpf!Yg52vX%D7#@*^M`fy7Srb z^Ta9wcwf$89uL61@qeg2vc&TAGKSLV>YKI3#5lfs#q5Zm`~Ogef!!CoWWyiA=J;js z%X_n!njeF2MZgaVoMh@S@8%lR)AsYyzmqkj+C8ghxI4G6O7ovK$udULO!2$(|__`2~6JjuoERet}kenJ%I0pU_O@tU*Fsd4gm&hV?p%Y{!;r}{S^Fv z_4EJbVjFv7>+dE9{rBS@8&_vbx9>4!8&g4JV^e2mSwlNR^Z&ujriy)b3jzqfYb35o z!;J+c>%LY+?P!IticwSrP;x2|k>j3Sxg2X%E2%57

`Lem|V$A>eR0uN8Y&sdjtu z%-lD<@61@6?qUPjUg|mF7!P7`hx+st`i!^L7HVHtzwnM z)LuOANIzT#9tU4)C^WIXhZWqrO;jr_O5aErkklzt)R-JmAh8xHMJ>x>OvTiuRi}FY z-o@0kFwwl7p|ro=*2q*cFRX5GCq-v!LPD)Sq+Uz~UkOwx-?X&!Q^4H)$|;=n9{idC z0mJl`tCTs3+e_EFVzQ}s`f_4fijsucWy5y zarHoT>Q06Z4yI1RPNpW`@4hSzZT|J`MU3i(GqNhm*9O@MndJ{31uA^i zXo&^c`EZ}5W)(|YMl##@MuSK#wyZ3dwJEz*n@C(Ry$|d`^D=thayXFqxt*WW&sWdI zdm1wv#VCKa<7d2Qc#qzvUvivhK5wq*djL7Wqjvf}-c~}d#G)eG`(u<`NGei`BFe4Q ztTSs?Gc8Ff%_5T4ce&J0v*FT`y_9r!Po=sPtHs5~BlV6VEUNzxU+)+sX}ffdPTRI^ z+qP}ns9yQgjY^t0ddMx1Yd`|OB{sHnUC-B;qum1|`tR#P_@llx>d z=qpNN&?nZib(t90A9F*U%1GbB+O;dq!cNgmmdCrK=(zS1zg*9(7VMfv)QMkt_F=wz zHX2p4X-R*=tJI4A)3SrL`H^peBNHh&XC#sVR3D zt17qeF>BaCZNlQO7n@@BuWs&l(FtRjaVn~wW^x-GsjpFH!ETyl7Od{Wf;4=bzL5nj zW9c^ZodMnN{3Jkz2j2;qhCm1ede*6891vR9?(Dy)N|iENw}HKLIOrjB0x)pEs-aS{ zZR$tEyZxbP(;(l43^KjRtSuirNmw~Bg&6p;)vqM*>S#L>0+Pw5CU%4@&)8OX2ykYQ z^f^hk-5%!QzuzYniL*1Gs#S5Kp_*ld1EAmkInP+^w?#(?rbC2Bm&0c5Ko@6`_ zi!Nvd391nu^@AmpZ$_0fPR2~kQGJS7lSGwA7U>s@+!d_`(P5y;MT#U~_ONSo9d+bf zVj6MgWN=|%#Qn;vl*TNLE$Mw|*89{yJ=WN>j{?T*vqa$U$2_dg46R)8wl&CNS&iK{ z>HDBC9e3b3roJd}gK!T>takKP);KLj_9T;%knG_fN^S$4hb`E|)qy__^=mm&Z{~CF zhc*PxdrJ@xRkQ-8lbh3Ys@2ZaR)Q3z**-VSgeMHE>c5AH1bpSUor&dgTiMd5Wn|(# z8Rwb{#uWZG(Jo0co98|mg5zF}M*d>gAg|Zdex@}Ps&`51({MmNyHF;GD4EBT`oP|X zd=Tq9JYz*IP%@2oujruVrK#jAT97|%ww60Ov2He^5zA4)VihJ$-bxoaqE7zU$rmK) z#O!xp&k$!TOEiC8+p6`Q)uNg4u8*chnx*aw=#oP~05DS&8gnL>^zpBkqqiSQA{Ita z%-)qosk1^`p&aB@rZ#)&3_|u{QqZO z{f{A3)XMprL}2{=pM$*`z*fY;{=4e=u7&=s+zI)ANd+V!L%#^2hpy@#N-WbB%U2Zl zgD_E0AVVWdMiFi_u2qqxeAsRzD%>l|g-|#$ayD3wHoT{EUS2Qe zEq=ryLi%iMZ`b}tSYzHInTJ{mY{OXy0)T&Rly3ippqpTk%A{T+e?K}j zURM^%!ZIWxW$32?Z&q9)Rao;#KQuLv+^ft>o|6c@QD=_}ql%5Th=cR{P)_51Qxjh# zRJW<|qmpRn3(K1lMwU-ayxjsgKS`Q7J5m0kw|LQb=CbyahnoQTWY z?g8-#_J+=*r`Jc|A0(MOvTc0kT-tBLIIFCd6Y5iCr>cqubJu0`Ox+FkDWs^L{;0mc zxk-nf?rxh(N<1B;<;9PSrR4D<*5!DvA()O7{vl9sps3x_-Y_w>qC3OI!_Wyza8K|E zAvJvWYyu)(z*TK7e+Q#dFWd_7%;fn4Ex*lEY2$X%SP9K9d6yWC2M!3>3>tu}g4R*V zRMC!~oYyF#Izu$lGjfQ?q}KD$rpDMRjF?f>6kuBlE`z4Yxy(Y(Y+Dr#PKA}UsSWD? zm|ER_O==Y22{m%cO1jhu`8bQ05@MlII86NP>-_`<|Q4g1f7Jh*4%=yY_ zafIlUJ2zA?dT8&WTGLE&gvPl|<0zKa=DLzzPOU7i#nate!Z3u|9R6E(6FZ|(EZ%+b zsB!MEkGz1K*oXGdp^tGOWyF0SI{tq>^nbgX|L>uTert_v9gIv#Ma|5OTy0(c_qQUz z!2+;T+eysD^IV+aC=aX$FPzbq+lZ7Gsa%r9l;b5{L-%qurFp89kpztdmZa8Uo!Btl zu7_NZMXQ=6T6+OFOCou6Xc_6tf!t+bSBNk)mLTlQ5ftr247OV6Mc0v+;x&BNW0wvJ zjRR9TWG^(<$&{@;eSs-b796_N#nMB4$rfzYM1jb>Gu$tEpL8-n>zGXVye2xB-qpV z&IZjhW#ka?h8F{QJqaK&xT~T;$AcKQD$V>$$-$x~1&qfWks(mJ8#7v7m4zpWw(NS( z5j0d&Bs4g)>{7yzl-7Fw`07Sj6{vw5nwVyVt8`;Rg5bzISP26=y}0htlPKRa8CaG# z=gw7__ltw`BWvICf>5(LFDFzC7u-Ij7*OKwd7685%wb6a=QD1CjpQs$^2~cx`@xS` zNMz6?Q4OgIR8LYa&m`q*QJ%!CbD#=ha?38!M&7yLA1Wn}M{$nV3-G0@@bD#WjCYI) zKFZ`bf$tFF#}GYZ7MK2U4AKI-GY*y(&DCt~4F1!3!{>cK+7XAfKw<)Jv$b1vHkpC;gl=VNy?f-RI(r=&j z@Dy@&vHYi$GBI*-`1j-=qpI@{qwt%et&>`VuG+PYzF>DUM1!h|8sz~*0>sA7|IH_y zskL`MJ4Yw|Ru~}gzgCOOEDSyuM+ivsjt@13h-SLD|INP2zRO|RKEDz$_zlt)ZWYQg zKHk`_;gygz9b$7*)WKC(<}zQUY8M94a#Tu_OEyX$Lej=Cs`b}zjTYvv-Jt6E^_bV) zCt>gvm2{y2tK8Uy*;ruhTa_?lSIlV;r8b zX?jME!z32pO8`g9ga%`RQ*v=F0O`bnPZebx@b#ZfQWvqZPAb@zl>ORo<_o7Dp&F?6 zP(tBH@~c-Zfx?Ulkb{F`C1S8y3F;;)^MwWBiBPQ1D=;yC{M-i~ILSfh3K!Ai{5c?J zdLm0OmDsWuV>%}MT*Qf<$UT+M=7pMVdJGRi-rdW>7iM&2UO%v@>_!inA`JD)lrKC& z75Y)Lg~PVq0Ge}-g$8cy0w@sHjUuwMm1|~u6X!*fGG>%bAbv5cEU3nR6&6o03J2ff z)*M)kj|gyvZ6Md8Y!m#IuWuP0<9daW2gPDp*=aQA2qm)VLJ($UUQ>-4&3LX|)=-g5 zDTzngTm?JwMM46$Z22o7jlr3Vp3K15k^@=c7JJx9WQg*XbLRkdC zYapmoZr8J8X5n5}a2xjY35bC^@Ez{}9JA&aex@>JiMr#&GtJGn$)Tt=HVKx@B+w50tPaNkh{N0!^9>r<#h(fr3kP@a(N1!O)$rdf&Dd!hhJNtXD zIbx!f3YSHV50oNza38Kzd9Vze|NZlyBd{fKzZOSB7NqO*qDh)*>XW~VnmJ^ zji(MF3D>tHCk-^y37b-c7t1Zrt)VBlefNnY+NH0u=9IPbDZ1z8XbK{5_W?~aGs@o& zTbi2gdn~PB;M%^{Q*d9xWhw;xy?E}nCbBs0rn@{51pJ@6e=LQg2dvlq_FM0;Iel9= zz?V~4Y+a&wJIgvt5@%1FDtB9(A<-f!NpP^nl51v_hp$v8$w{ z=Rh2*Y?stNGlx7wbOLqrFbxg3lqpaaN{@9c)nNxe#D=Xouh@g7Wd}stZ!B8jrc4HPmOW%Xt^a!LcN8M4^efD8wWziBkha6&KggDq^9beRoiLH_z9 zGUiqkIvsoqX!3F)6qr+_HfB$D%@)T=XV3YUews|Tg-Hwn^wh3)q=N>FC*4nHJ+L$K zpR;I6Gt%?U%!6mxrP$mlEEiT&BVf$x(VJRuEIXdqtS+qfX^-@UKefF=?Q z(jc2Y2oyEyr3_bP|F%)C?~RzdfbNXgw%b_zaAs2QbA_QL+IyP^@l+{#{17?2dn80k zljl~W{3$~wO4E?SSij&`vnbpKCUzN%8GY^!-wNR8=XKiz>yng^Xj99@bTW|TDw5XGfDje2@E z*~-mJF8z}cI1eTpHlg*7?K(U5q3H%{y84gCiDbksT+HB=ca!YVTu zgPDuJzB@76rs{is=F^_95WD#mg}F*~wRr~vgN4^*Gy=hUUD_~f0QPh!&J7XP9zv&H zY}Zm4O#rej< zQmBNK_0>1jXd)Y3cJi(*1U|!mL(;nU#j_WV33)oK-!s$XS(mQqWqQ7&ZZ54iT5+r| zi|MH>VJs`1ZQr<{eTMqC#Y~41>Ga4BuQynUV!QuZeaFa6aP(B)SxC~V-r0K5 z5BJ<3nuAkX12%0k5qI=#D*PNg{NNjn>VUnvH!{DfD}FX=e%E5lw-IZgDqD$1an(zv z95TXS9wGg?Bl{w91nOC8HvvD1&ENr~L>4u{^bNaBD>ZHXIw1Ko!;wjz1%zZMbWE8# z7f5xlDTQWK%rH+)0KY&O>*EHs@Ha5t9ltEE{qv`K0tO?W=jgzciZhHZ4As;i<7{@M(!#&K$4UGQ?~d6rbu|rCYd`D!Bgha2*v# z?6){N62Wq7br9`S=y(rk$xKExQsyv0H~Z<~f!Z7~Wt6SlJBO4_KeNahC?2rxh%Z14 z{6vx|=@Pd?8vwjCEbf?V*zgc>36eg4u4w8WMluPe+qB=i60{qnN+XKmud{LfKvd^Rf{8@jDa#RaXtvGeC92KvnMDV3m2 z4Xt7QB96VazV=Z?RrMXb$#mb85@y7X+OE;c6PL94T|ssUhD|n8IM`GhqU%%}=6E(! z@O+LF*%Uy084M_#De*pBSU<)G3|%go1vt<|<(ZKk{3&*44f?ftxS-a(+@u_92o7ot zYq%I+Ztyt1x5RPt_1it>&+05XbK1B{-T~aA+FN6BiF@>|QCJ`#y*u z@e*p+J|+Jzl4qtDnLJPde6Gl8Qfu5eP#Lr_}cyBzGaR912ca0h5s# zbgocm38uvIstvyAPMEgVj^>{XqR&db7$(XJRTRiR@!lH>>CTe{+zRJEgcn{?M627> zsw6}Y)J+s3)u#g*Mo19)oWp785&T@;fee1**^o5#bgS4epuPWP>~Y2v-~{)-me7SK zd!AQUXsd{A=;C;8>vRTE5Dol&>XJ&AYMijyXV3|_46Fr#lz`uF9dT^PhX2e>lDN?r z>wx*9-Pr~siloVs7@`dn*kGmY0xP)2odnz6S437Hi&}MSb1iiwEiwfy=f;yg# zDZojIe7{n|lnmh@$rU>6-%oUGrG#^0y%z_Niq4LG38Yq&Dq<~B-3qLMHLbL;&A)i3w zq0}L%{J2P1a z2OC$%f4j5C`~!#oBU=IP{19v?%zqxLR77sUDKZWk1TEdClEz1yHB10F7>l{;9l0L|=ADc&?i zK#F90YE|)m(u4LGC%M^0?53NrH3M`xl2{P!5+fC(H)Yt|t=X~m+os4b6}Wj|nDvL8 z8n=Bhi`Mq$&2sm(8n4F2)~_ylMf-R2rn!V)Bfzhv7v2SF{79o}>ITpgUpe=zcRpds zp^3fse>q!&ohi{7gYJM|qD$1?s^vyP1XP=26O)1AFu)?|OCYHCJm*LP4*zJ8Raq1u z)9(U+oYRkni_C&!f4&%ORK?w$g6<;rT((@LunPCC_#2P zxJ&Q13mCI_U+H?IvV89Y)i_#NnNt!>xavHwF$|O zXuHG5oCo;G6F&W`KV4I0A-(zyjQ;ws!05mAr~eli{U77e_#bTiA4Hr~$mBnaBxQ^3 zlOJG&4aI|YIUi&Z#TBHjLS(GmY^z5R28NolKW$l^Ym#0I3|0lI-ggSR?CgqX8f;MBaPl&YzSG} z4(9gprQ%M^N3g+r;f^a0BNw0BQ9}e{Op$ssU!0cTdbP z1%BNUh*RkAe#+jya`#(*p*uQ|spESDMarSs8h3e`E#gtvYi=8d#ADvy9g>R@*^D~F z2t#h@kzA0JK)w;AMPg^lWi2XAU}jpiDF!akXK|rSi6}wmaK)KT*81I6M}f%l3XCMR z-&LC;?s53?Q?B;UuDeB{5^S+oOfSGE^CnkvgEc9^13~<4(iGap$VY8}3$6;-sL}t1 z4d0l&nxB@pZuYHH` z{ONm|SH}iy2^)Zg%Ou?*Q?I+u&ZmckE<;nVG0STB`M9GzLE5UAMeRQQJzJxXBBwA&_T6LHe4yGpP7i~lax~#Ub5BlJE zg>YF0Yn0Wcsv`EJIW^d7i>M?PO5_+)OxDS;9?zPfCH;#_rpR4-*9!|aogttErPHlR zUf2d~4Xa7AEaZSe)Mn9=Nd;=@JUDKUaJU-Rx~HXERZPZJTiBwHdXup>tP-Z$yw6H? z{D8e~w09((x@w&~)75oSpJ7o&u#DUKXAP}9afG;3qf=+XWeC!=Ip8PJvw~{@B3H)k zZr>U-w?x^Y3%$zAfoF_*V2Mlr?I=_C57F2k-rurm=_3`CHmW^yY`ye5aJG#E#oU&y z^R4vJ!2z7aF;V5BD1dbHn6(R25;-0cu1Cet+$J~Uw}=H_%79gf!-W2#1g=S`%zSN- zwVT1}5o>Hi-DpkU76(;YW&Y92O;@cEU^coXt>XfiRWI$}_*t&RQ_K?A8!$gpQKZe> z6VsBW458Q0>X1E#m*K&U%))^SmEntSPBAZb7VW{C@EA7Plo3r-`7EMb;;WeQn0bRTSxW7MTSYNoW=(qCsKsMVCbY?$#Z{|k#%NHM zA*6=sc(VKVE`UVqumIooHMGYRSh$SD{ErAy8%i_*n<=4ODdFErVql6WIx-X4fyaoz&jU+aYlbi=W`&5GJ~zS*@5IRv9cn<|il?|!d8>N94!OI0)aLF!Q0nlhtv zV$SFv61Ek9=p#mMT*~J{BfjK)?1ss~7B8LE@RPM6>=Q&sCt<9ZWOlek61x3T53zDy z_Ki;P_XP~dr)aCdrp;^Xx&4zy791bkXYcFE&ul#uoMVnctVZzl-Azp*+fw1N@S40^ zWBY6U4w+j|T8!q!)5)=7rk~;72u(J{qztk$Rb^WOCbU62Z^s|pn=)TqT4{gYcX?y1 z?|~>Cvir?R7Ga#&UI_thW{axhKZmGsOKK2*Z5|H*2nrEoD6q0cA?LAuQGqE#iVxT) zkKFW#vDut&E=}&^_xyn@nKhBk4S$!WNK~%$ z0c&2{SDdyuxlzV0ph!Peph$e2NH|n4;u};Z5-fDRQCkV`hd9~Qhw#l z5yeB&7zlX?y>QU?3e8P%Gzk1X934Q9LPIvcZi~Q>$tU#A^%^O!FsqRvO1M){#{wo# zBk9bs(!8G_zMYJ-^KkkOmXlld6&M}R+at4#TYfha^(?3_OqFsw=T6Gudap+sqFPF0 z*6D8MYBS6E;rkj8{7GbNPpnUPv9*l#u0T^M#yAbod>pw)srdC}u6;9n!}f|*m@!$~ z1aL-1&ei+i_Mkf0!?>5p@ss}z+(4GaIZ0Tu^mr{+M1{}bS8k3r~HKz!?C`p>TW)1H#Yg*vr z7Y{a{9Z}e1N<7QR%urOa_cLshyVKNaKNU@l7j~j>PeI7MIZZ|r0*YSjU6P_&ia|jH zDoChFYF-JCkoNDw*&*{QG3x+J%2L5_4`n1Tg9hatvloFoYL01#hFFj~!}MRSdgSSl z=m-yq{#uwWUIpuCs@%BEy5ob11|s~&TVX8~-XV)oMfeNdXD?Z9E10-tP#Krhiv$@dBpKj5J%t@Y2xI!*8s~Z z29}0zR`_9s&89Brq4Tru3F{G&uQu{ujBFqN`NY$Hb>qnXc(a!g%hbv!R@n6sNonM) zg649UVVIiIE)_J6eMZ?R^6HGdRMn-UD36*c8_Z2r&xc^Cs2p^v6x-_j{J)k91n!wt9I-~_PA$GNiLi=u7ixtk`YUQ4uIF+`SI~U z1J;MiD+DHLSA)nBsc8CJW1Z4F5uFXI0GzFHhs4egAoxF&>1&8*Nl_OA^!wW4GJCRO zwS%7>sOyj*5EN! zUpux=mBP|Q*_J!@%f6V&EZf{?`H}D&1^^@HO#Gta8P{W+FkdO5OW;fnD1|4&tlh3} z@YGnJ3d(Y0t#ep+bksNs#e?8*u-V=@#Dvz21#EB=jam5x3MtG&IuRHU$pr(K+Y-AX zn7FqKEk!?hw{HWBS~^ioY8Dbe(VtwFva+1h5$-}M9!~UYHGIL>zwFFN1`lcLe zwaMY%;tKHw`EL=C_^}jKY3YhWzg-&!anlG&@4E|`Vl}0q!EvCtT1I@}=Ug2;8OzB) zmllrTJ}RHtO2N@|-7)oaf*v0`{>2c|j?-t&WbDWOUDsBIUR24HnS0{I;>(%9+r)y* zg2K$nGPerx{E6HXH@h?eRQC~Y44A2^$`xKRwnOj_7pT5_!?K%>JT+F+ z6(@ZUF%FqvCBG2v8WL04A5>D=m|;&N?Hzcdj=|%{4JK2j_;hMKOfU}I+5PVH87xo# zc>v2%1gFE>V^6x3$7#ymLM62}*)(ex+`ImB7=eUwa2O&zcN_th9iPz)#fXNbq_VnK zg>+Fagfb53(>-Y^v23^|gST@kT%3pG*YUyrd-zn|F0Cr_;Qh)MO;mTE$%x&%B^Oc= zO-<|3$Nplt0sdxXQO`|RVIbVxm_^24G_6XuTxk&{Yyl+?OeXa-!t}8&fuTGLZpS|{?$S9qu^8TDrgtdOu`4*Sqx20lCJ(;z6u7&0EbrB@495}e zvjfw8yG7#Eo7QX+`k$3*tbTCwGm9LGOvTam&Kk&4&(T!!b0d-h(+s160p@Pn+_M|) zwasiA7r)El>t5DJfiBLb@2=gQDN0N*FfYuh&F<6BNcc)=oqju*S(+ucbzy4pyN1%s zgS@}T`xoCKJdeoM>hW-Zt9xSNRYI8RfX^{UPSJ}y8$_k~4-2G8KZDJQl``0lf>>)j z^q^y@`VIX~W%W-QAF*8U#?c|>tGQ{a09;)CL{-NfEv_2<$o(R8`V7xFRTl$)d~KX! zxG^v#xd(Z9R*`P* z8NwYSrl;qaYDzF0iB%{|A(v0($}TDr##;!y6paThkw{fnuKExakKusCdM>46hESJo z6Z4inrJpt`IzSB{l1R?`XS)o3@M9OZsiP&{y4g5QBH!U*Fvdd|9inn^a}Nz>2&)`? zh!|tcpGBMA4e|H2Y3)~7iyNUBsc|aN0$HM9Uc2MDIL(61;J!I)NmIwv>&&25`&+6M zq1}!I%Azc>=L(6nYlCWwU59Ea*szPa>sE|5)2pJsAnOmce3ZqxF(4^b@uZ6D1K#-5 zD6|eu@+l+j4}V7yxluQ@oX?sla^=5dw}yP&j6E+69hswg1L1c=)OyvZ7^wHQJl;ml z_2lX#$i;=Fs}vkh=ukc4y2Vj2Lu7vAHQ*E%@5?3`^a{BzDVU zF)O4|`;uuAO@)kfdwp~fqS#rR$4Oj@c*zBS`-fL6qu8<7qzl8rl--^kjiCV!(vbxC2vIdMo2I^X@+ID zcT&$52_`~JOBXh&mXX+ceO*m*0_=9ArqG>xjMR;+M=q{e-N#QEj-BCAzAVeGSrXNh zCV`uX4qS?7l$u+*J~5P?9xlU2%6rgo30lJ)cd|FHtEmloD@8tO@5y7N5t*NZN|hrm z*0FP5k0_1u5$>dp#I>8az>my1NoIAqBZ!Lx(!ohP^U@&Vmqd8 zH=75V+`}JpR;Wj8!j6BT1WSjMs>H+3_*52JYs(04P<@$3WEVZ7V%N-CLN$onNB~*- za-hT{!s~K{EUyaw7zDbp7n5T~SRV3$*>Zhpg-*51L=Zj|oeHx)1Mr4juj_5;_<5%8 ziMWWR&MhgdLq0$}U0q=ol1xb)TQBdcV!(3$iF4x~ue+F-gFAGMn^|`*YBjuP=jx!~ z06>UuQAq?Ix&zn0^To|<4!CSXZW7o6VrM}5dYxV+Q~8-h^Y9DzNs{5%+kyFy5cysy za}2EkZyRxQ^Rgq)T6r=({uw7y@%D4S?wd{Ck@D0(;mjg4NbY$Z$xd6rCGrNITO04Y zO%6aZ!9hMp%kU=V6dLc($d`AHMbf`&G9BXY%xr$$hovCbBj@|K2-4_HjW4Xn{knIL zaKV)PQkC?JIKYK?u)1`rzd)G(eO222!%q#U6QaT;SUl*MO9AvJ_$WC-@uTOjb58L_ zQo63V8+G)0D~=S&a%3>qqG`7N+Wfi$Logc=SXGBq3&TV|=!!;Nzi4VeqP9=hV>H5k ziX8p2v_i>9nc1rQm(7T8t#sTSGnI9T#Ms(_k_%sm3mT6gc=YrdUm@Ip6xRqL0H93*Yx0O!3Qw+_Y!81*n-ovS%iBlXx62TFNbk8K-j=LOV=1s zwc7i_TsS%sk!R7r81r4v*Ec`Rrl_m zr2$@wBrDGJ1`%wG6Ar259e%+MkZzK88-X>M^WgfA@HcWJmPUeFdO?d0>gvCTn0-ZWgb;$}~gdQiffS0?*jk$T`izb=V-&N#O_U4yp?Y!Mdlk09!o82t}+5dEvSj%vN5 zCBperFlf(sXr6C$n?zYvm=YYyz=~W1tkhvu1wODh>tKoBEiRB9*Py%96luTxm11-k?Q=g$c>y=q9%J< zVbw|kc=&DAiz8G*&G@8XlevEthbWV6a7nM1@VjKNkP|sl%x3(c9h#|9HIdVuC_??C z!MaVTrRI4=oMEugDa}D)#f1zPsr&vLR0Zy!7;QA4?x1w?=X%tH7o_(2z@8LjA`t^# zft3pe@**E=P;MFXEB+)Zh$?+;5%i6ECfT?A^~N`o&QHR5@V8a13HuA~omH+0(xm&s zJn#ru(@aCcl%uY66t2-NPi-*^o`hAyJ}I5kdqib+qh*CNP|jg>f!Wj#HJ<4r?4uCX zvkf`dDbhurH>#bk@3|Ap%0+kV-0PkcrZb0Q6)EJKBfaiae*!zLC7wkQ?cY#avSAHH z-b1`V^N9SgFL7-JrVQZS2rsHMA5v)j^@ga==T4XfE9yy6w7~pXILh8O)Le{Zg)9`|o`-$nca zc~hvlgOB$pGXop$oW3PzOuUbE^uRf@bo%^%%GEHQ}3uc0E<9SxbN+Fk6DEin>4 zHcD4f(K{ENOe$J0HJ#urqwE!{iYCcrgQT6kUmRQ&pZsx(U*x5m938GK3cceA-25P7 z?4_>Rtm;@LOJc>-Es0d2lZed7(#_R8eGm|eZ(xhjbvF{TQvs1jaS#K%R>_hqN0n}TZ* zkc089?X9=$pO*FdJ8a~1LwKU&Tl*+PUpFFBdK=aX&m5jxjDg5G1pXXNL&FXtQoDIi z%I2VE+_J15PN$4XB^X2Yje8=^qT3Q6Up)7auJ|SXIn8t2lJM#_5ql$SZ|nXfb&U<5 z+WD;cxsrkAy@tew0gl8PHWX0(qf>97u#=sJz7BD=`gp*W%GmlPa|+rCER@9rjcWg_ zl26OYrAyJyc>(x*jhp9DekXff;UF2NN;Ui}MJ?5ICzv@f9ALbJ?E#ZUr9Ic3 zzA*o$&I=Ta@JfZOEAMmeNUz9k93p!8X=>FBD$#aW*rJBSOJG_{E4u;M3A)vn3ZA*FCGn+Fg(4w7}cEUuvHYjNe3srT? zjGbTt%LY~=@?&|zrxYJ%v<6_xj4<+!VwleU+BF+z4)}b&?KFik zy?KZ%qJSTxm)WSC(-)vC z_LTIFihr!^y%i5PBEEPCOyW1(0O<=Ad}++TAQlUVUet+p^E3c}!Hm6Ker0kttjBIWHFAYVE28@r68QPb>)Vg<;d0ndg zIOg|&%Z^&B5koUj%;;F55>#Cd>y`X1^41GHDSIjVmR%4uBt$XKaBh6+p3un1m6DKK zM5nC$KuQFHa!O+A!tnBN$&WmSvCPz#nQaEXC!g(?sW+Y@AB1kdg2dM^(Gjmzs6*J zi>IYc&r4tXJ{{+;xx*UGux7GmUyf}GKo{&yc+i^CQk+fM5xwnR=XN< z!u~>Gl{|8NtTsKC_us}+!JbSFv?wd*)?I^VPt2vT`c;a6orPS2Qhe`>N1KB~dB}yP zspLQzZ>`?Hbq-7qJC#l@Vh{gOd0-=i*!QkM8LpL1X8-}g1mS#mh6v^#lwH+V0EAht zLRoZn@;eAS)m=80s0Jn#+sLq@zuIq|XFXByZxLIoN4=#LqQuVVkJJJoqdv}YdIi8` za&=Ppx)n$aP&MKW_^PY6l=m-iPXIGakyd*1%=})EsxHySwRk^AE?qcrR8hTjF`nFh z)+UT>wL0VXkVCY=24X|7B}!a=Gf)c2+1jXZ;lwogP%J5l_LHb4lWDj;(dv}Vr1IJ% zBzmFhafX~i#<1bqv&puIYKuHOPY|K%X&v{<{=yTL{$8uDcy(HHi}VDVjHC}Z7W0`b zEvA9p60jBWkkB5Rk#%5BJPS(P7jy(H&ZM=!PzvrzF1=cb@j0B{!WqXMl>4hvAUG#n zJd@sf-hvm66(tgSb~I9O>_*OH9ggr<9(jkPzpUP5U;9oi{-`RXFkT6&7UzshGl7YK z=w!GA{fajfE6<@$!92K|Md|hQp!i-X2J~nt=D;7#M2;}9l3LG<6`3C2w+L(}Swn*C-B*?`-k7j87(HI0e zOg>|2NSSo0G$Db|yJ=}l3XfUHc3P)1NIM4OhMgn9utTLY8mQE#BnS7N{&WXwxbPTC zj>^Vmu=6JO$5zNwB5NNSl0w;}jb@J-VA6wNi{X~PSBBYYx)&mpWiwGyMd~%>340*O<^m+;13xv+nsl@@4vWer8?fJpf?QLDsIAYG$AW; zLaEVbXdlU68j5l)of@<#27i#8e9acN)RqV5SD02bMKnOYW!RB{72(fvCCTBSVi?ru zbgDA#*GRW68N(c0E>5u>u(SP<+gV#x)7`Bp@SBKiVu<5JAQnY_TkLETuOirHXdSvS zvj3FIepQF6dAlF4aI!UHW_6)6yAM7CrBvn^#Qb^(|KMPUas1SycQijlWVnLIlvayxabGnXVuaQ^dHa@y9)=$QZH>SPegN=OO*~ zE)SFDbmX`%K>u)QKvO4)0Q6_1yp?lfgooarhtt<$z~YTO+(JVl(~ASc`owLsRkis`U_?MIJW!nR@Mo{TY+o9Pv7gjq0Br6 z69CC^k3Y>byZiTYSu$_l7lJPB2#srl$j1$McL;9;1JwOOnTj&h4}mWH-Vn?pBA#s3 zjm-omv~5W85u0g%GVKXOn)WQaVM*sXOrslhX;tKH6?3k};k`m#5;f?oYG{A|jfzVI zEawoElA5$S+%=j>B{ljl6OB6dMOtiz$z|zws<7A7tg64qMADNf&^>0E_v(v4Xo_qH zV^U-nQmvG1&4lmI`ITySApjtTHJlbWG-M3T*jAxeFp8eXd~QuT_;Rtxq6gbbb-=tw zoQ(PY91W&wSS2@?%S!N+c&XI*-Qe>8h;>EoRGL|8iL5JVmPFo`8mCcY@G7$%vVy7X z7@ReiXO;L?;tk6Mm3?VrP%a+9@9N45(_m|XD$^pZCLI=|=N&b3Eye{UTf~qseLt&P z!#sl$Vu>mfVC$4UM*S1iA&A8WT0&j2yWtx^d_y<4cNyNemon|ChjXI5IDRb_6+)L6 zHL>y7N+Zt&p4YiL#W9q4j^;U#_Uo|iALm532s#R|g|RtF1ga%u9(|3q*VEV07-Y_# z={jfTg|b)%84CRox5B4Px#rve>wV`e>F+Ihvw2o<_Q-Nv6Oskz6Xf0(P5Qe*HQ7l- zcH%D^p0}1DkU?Oh5Luxsh!wO zKUM!6-)%F>W(*eN%I<=x(m0rDftloG$@?ufi_0FJPvZ3#aSQ)qBP??BlZ)n3kR!u( ztnUxe)+T0*JsBGnx*NQaQ*rbN@u7$&a*QhLA>#~Ru<77+YbIJviqYiex1fq>1{FT# zFdi=DsQwOIHD+foydCEv&;U6m{f)}zJS3hga=b91my!N=YxAFN>}t3rbzl6j(22F3 zN=wsJ^$u!O$eS~g%{1`E%Z4(MfN(74t3fvCmpBFL^Zwb}W|;;%1`>f&|3*$y)Z>cJ zb4L4u3{QiD>q8`;X78t!poKbPNQ3F!N5@gjzIaM@VHUUjjLWq@kvi9sqbqS?nXGE8 z#+GiOoSb3agPl)kT>OYk63q+oSkS>R1&~Kn8mWrR@Ghg2kK(O=B0gr7cqQS&ZU#=n z!fuWk@yB<^!ZQXKgv|$6V&t7P%_Pw;Z6eX>n7u0VO2tT?Md1A_{XTzc4f!^fy@J`@ zL_xHu4pQ2%+0gi2MYpK?iQ^gAY+ZY~Gl4zpRA+4JCqhte=){_!sS#6~-(u2O33{G&qyu-3N|Q&_I& zrYu8ewgXs?(VGq;pSXyDqUfrqm8MV7=*kn-gajV?A&2rCKCU2b%V#8DjIS?*Vby zKbhSHwl(aey@M#B8n8X&2S?C9fc+T=k|2m>1p1jE^8a*p7GPC1+y5t}yFEv0biZjerCkVf)}=vc*AQeLaes5@b#F77Z6qAz%l-99zN7!krPb@WE@*haV*6;&%ac`t z$p+!J!?T5Q(0fA5a}OU8+PZ!Ndhf30kT((m^9FiJ79WS^vcFZ6gGuSj{S`e2Q%u8$ z*$=`FNUwnT3MQXg2wm@iypIy_wtTRvyLm345nt~Hjh{W&yk9bNXi)x$TYOmqRkBjR z62UrkX=#b5CsQ=dI{nd9hLOmmydWim_?39xb1J`JjsCP(>wNM~^8+bwt(VJK^`0=s z%97EYPT=bjs((ZFX-|N_y>DS zvWRyIuDcghz}MpyZE#*nQw|a4uW0zgqtA>*CLBdpjUhRD`mJFRa&;l=cRkT3S(l<+ zO8=_HSCLh~y|ftK(ajUECd|EE=Wy?Hb%c%#nHYPZLw9akcR7u!w5#-PioD>8RhE)< zt{&UjCzWN|o#^vd8j;6KXf=4}kMkCW| zVSxvE=u0vh*r$0-S(9P7Q5CW%^7bKVu=| zk>ZOJ}2*@xw z%?i%k;pi|RUQ44_+hrd+)y{B|7lfBZp}F!E)I)8)h6ld30f2zQD zTA+dMr02cDX+vCzfK9iwIK=x(6Jyzg^uR7;c;;@nWi3y`O@AqwhJ>;X- zN7gfZGgG5gwbGh~E(12E`qln~DWZnEFRDh%yxmP)2=<8>_4(`U0+5>T-4EU{^0T?< z`+eP>KTJFH+2mikxF_l^Z@%c<4BZl2RS?NPZ1r~7eLM)%xk}0y=Acd)Cm(z~Xvwb0 zQk7zx^wnc%U@M7vM_a$zg(1pPLqISuKU(`;+GHB;XjQ`ED5yW)tP!0z#M2FKs+Ds` z@d($Yzm}Bw#6VTT%Ge5*n?cNZ-1wB^I44Q442Ll-=xb?uqN`n``RUrAJG2xmJW}#I zW1SCEJv%R%*ur!4a{!F-lTBUWI$4=GO;;xgrKZ*Jp3sa<>ilJ{rnNT~(~B#*XEmiU z1~Ed`QBgYpk>YsHbLx#%E)o9--i+ZC9f^_7T3q*re!~_iq1d4WhP8%?V(#=QM(g^7 z>2+F74STNRx~BuypUTi!+)M{gS@jyMH($ZDu zKjsY7wy_tY=^3B$W08}!&<@2c!l~K6&#D)VB-K$kGlCyqCHZOrNP@szFIP8$SAP6l zAIjazY5FRXfEyma)Kg?SYc6gqIrvj&$otnW`!RzBpQi4fq)s=P5CdQP@)yndY7bUH zan{vp_Qu7}wY$KTn$j1%Y@h6=n?MZNqDJhm%WboRANR6CQby3{gRzTJfUkwKimRra z>v20v{=}dJ`%D)e01bVn*OnnAnvxkDMidvnnJEF&DTbM&P+`Ujq+6c9syhcdm!joG z*1W2nVX)Y4=7jc_kF3u24hP6*6e_ugdd-Zx2G;^;ugxy^C3B;tZE{9i)S#}n+Tm^Wl z^%KpO#g^>$))G%Ak1-6LUD#ZTRTn(7!9<4(>I$Q9zeW_j9T{_T6J6i{a*yI=rhgd@ z)gG{9+1{|l$zFGeY|`t&%G=$#LakN(kclKjR)UF-Ix%+c&+>+~j$d4Qmb}LruYMO@ z`qpSxlDi`75!wy{eqU`gG<%ZOL3iz#AK@!h!=>|j1B+Oe$GKu9eUZ!k_(1T+S7_kA zbJn;fO_sAts`Puo#$t6E;ze2?q_a>$w#+0nuk}*bYY8_IQmYk^aF^PtEnm9%vS?g- zl=f(*i$v;};DFLu)Ie}{;wBfYcRZ;#gqu}?q$J)G2lLswTD<(sxB!k1pp9in$Y8=k z^3JyAcETT9MmAB~bYMX>W~mpKeS-AdzQ{3eH)NL0Fva9G(r77Eq^5@T^jqfFHlZW6 zX`)orA@BS6J(?KBp+#ABTs)dY-6)A)m=B$=fl;)gp0w5h=kVgFEy%>zT==t#)Oswq zTr?{tmWGWFbDOksn&?;8ZO@~z1|4maoHqnx;)hZai1Oa97qKZ2`=>=Tqbi7E&k^Na zZ{=(CC~B6eo5t-^lBcfd9J7-)zKvBA>K}~;QMU(%+w1B)Tm0HTIfLh#lU;3Yn~+}d zUP0S|jo8kZ7+vu!d=$BZlVeRdZn#XTYejHx3KQ;O9%HU#dW(r^FcXBZC(y~Sm~%N} z2AJNk$S5a5XzSgPM7Rj`gO_&{#IQ+BaJI7%Cg(lRcrdBsB{DM zT8d*WSa9l7$|3s+xddzetVv2FvHpTmi>HO0ST5olCxQvl(GCf3Q9y&j7i|TuS52RC z$Mq$-RNqf4At8+FuTKP}#H=tDX#`r?5dsa5dEA@$R5+ZaAl)jTIpWtmtDot`nN#*n zhU~NvwXJ2@?Ng4=Ga)ngqKekQp9>riEd9DzgA}4BUwqIm0%Wss9jHUl$nKYqO;2N7 zknpSn9IQrcJR>i>8i4TbCiE{yOjELbLUDeF)~y3Xq^W(@CXkZSMd`R;HHADm=DLkJ zS;1I$?g$Acj(p>KT3D?`z_4LUo}Uvij?k=_H9S~+>bx^)AG{@fB`}K$xi6WJ!FPJGW zB~LoXg!SC`+S#|tF_WQeoMF^8u?W?f)9v=3VwpXM#@dD`br&6k3%WzaC(pjfR0`fM zChRRAn~rhB-s|T5e1XI1$7!j+-kyB4Yw?uPR@@9KfpTk%nATjRS13yeX_R>U?NRR* zYr(<$9=%ADVmjc*1V?@FRwNrtIjAjb6~xw zC-sWFLtc2tkj`HGvT-)9R$lY{zLj=HPa%BG;Eej@!{!SgZ7uQSkiTpuyam5P z5rGi-YQWO|GMX=FapkU`5NRBgpyZCbC47f9)TZ5%PIz1ivCfeoh~;Vbi@p|Pw7gM> zwb+um?aH84>hd{#m`B&9Hw?kAeS3;L=R7r;t*zfqC&7JCTJ}UUynqaE9fG)Oeo+9~ z<)#K&_ox+Nw&lB+9i|2E!p?w#If|`6#-*70{+ZT9cyNps75*mHJhbjb(M$RiL#Im7 zkt@=c&>5xhMt!=^u@mJ>AD$D_6u+1VyRkNNNm4B-5;&h9$MT0M8s71AN$h*tvfb!k&(H`x-=+RpQI>om@b>eBy%{M}3KN2#u_7ZsoV&Xy#uDxoRl2 zhZ9oKR?*q};PbY(m7gWgt{z{7YV^%w zc`Y^X^W2*`zFzR@pZ`FAYXD7ajJxrE>}I9XGO?tURZlH3Izhh)mjN#;L|i9=q<*Nz zeJ$l3es%o;Vkm2YSg0p_sEJfD;4905eJ~)3KL*>sr?_0fwyGKtmV*Mx?gOY(=^nPy z75*rmkv2($3TAtHYhv>G)jB4hBOwj?+DEI7B7nKguhhz2Yd1 z5R{LN%C|hj+rB0#%?eMKUp2KkGARiM^w%6HC3B_ajcD)SC*>BKm^LzSenJ0Ao&OwF zP*SjP9n;qLfKIW#zSsN6#KjQ=N9BF<<&EVWEqo{0Wy95oba_&mA2}DQZ?GFIAE4+$ zTSWyjBPuJ{I>+2{`XjGQUK|-8z?*tIei@>sC0eceal?yJ)H4CGLcpm&tzj$W8yN`# zWW`Z58t<@KB$*M=mUB3S1Ewuu;KvZt)Q44I^sc9(<6KD zz8jzDcL^6W2q>?&+~@GAhGm!bSVyKo4FcZIG@w+Qpt=z*Ug35;iTEV_r3KuuIY@AP z86i%AyiC(GJ?msLDzV2q&uEWf<036blx`(bK34rhL@TD$CD~KAPmc@j?tv4i(U$`9 zcWk#E6!Y?LEsmMJ0&nlU1XdZxd)a(3uMfNLXuUp;?^_>tzV(jaTa$0?-?6+ps6I8M z^B+WMTXsb|tcon?N_dCOn5B9n=!X7x%?0 zTWoPArre~5nAqwvGIZK;G@h1ctA0q9aR>+@?}8?$AnXuMICs=!+GRwXA9E?Tb*cs~c2&|aJbq|eJ7f#q| zoxW$gW$NCNCCs5dI)Z^%IkU1tA%66_qyJRWe0$h5=C+eor|YD9VtX=mo9i~)qd6;iM;BM3`Er9%Vbh*xkQP$9s^g?<6<&loxpnjh84ZhlM9LxMJBc zLXJ0K3!L}(&LVO@gM{JDV-#1QVN~`dv!T2 z2Qn;Li&$}sd(ekuw=gm4*!C?zfH%!{5U? zO_#Y7qV!K-j*(lr3xK97+d&CUgC{~Jh<6M)O$r&FwN{1 z20nbi=4jRBh^n!*wjSy8azByNjBI_hrIYM>2DjX@lKe#Cjb~HNQHwH_8rD&4I!0l; z_yD1aD4HlIRpaTe{;-Dp(o62$P92GK;Vp2_eF?x?niw86wX|gzR^&6S9>(;XlZu!P zg%R|xezBab&$a_p^tvy_W@JtUC?XN}cgE^{$r@Jj0O-eGw1y~*_g%tgOnARkghNuL z-{~{vK;QbpL8{T(kM6bO^)h}ux~es@-LTd;R=9)sxy<}5O;v>vrHj%91Z$l;<`Y(w zbdlOcHl_DeY2!3@#q;ILT9*;B7%PjE-TI@nj;lVk>o~L@x38XcbQ>sb4Q_ergjle2 z=1TP)RfEaI9>j4(%Pj#eMlOU;E^SAsx1HlY$8Ha+YL5x9-9of5SP~`Q!TTkHjuEe( z^@Be9fgW2rMRKH_{6?-ncAL`peXi#-uUai?&<79D<|qcq#{*VhfR0^Bu#$m}waU-a zf?oVYeZ&@3KR+@Wsj@7H(vYJuPF8)?g;g1qgAbPp;Ih|4hUftITYkRimR-QPGaWd7JcGhKSRpMGT&ZPF3KZi+UYK+VsaLymr zv>(Eeqzvw$N+M$wu# z>3e49=_k#bazg|41_rGVT0nT<(dcOP7(s1Ur0>eqr0e92dZHT8*{A<=?8f_)wMpo0 z{|aanXhtrN0z4$6y^uuRVHQ*`pV$MvaOW$EvoxJGG@+{pg z{B(^TDMUY~v>>L4)O#sr#wBegOIOE&*2iEbQW`BhEFF0u>@prRi!1xGtL|1g#KAS$ z2z`cSn6L;ja0_%*HV*2mK3AE;kjTw^YqTooD;21_$*D_&YbZt7kr0YIgDiIM+h3av zgXsG{{f0}-p6NrnC_K3|jZ}V2#|Q~}&q&yQGGhGuzGQpOxN92O13je4X(I|k==cr~ z){SHv(u91WcbB0wZRt+%i7bMlv;!;=?yyQRrb<4vGj{OKNm9nxng!4NsvZZwIjObb z@KC~nsdPY69@6BqZ5_xo2)t2U7f?&S-~;ZL?M-P+2NvUqJyv1rd0k&{^ggm|X#DvU zA1-EY8=0$XfC4GdfipYcF7$esav-K`gw%(SpA#*Orbj6niv@8kHC8^~J1)}`9(X#r zWe+dN@#5LahIxdUkkOvtdVCuX)hsK*ev-=yc~?~I&5QnUdA&FOi2aQH#JHqpMANea zI;p)iNmoZdlH(Y%N7`Q z$tJQ{7&y_+s7g)E&Jh({721M{ps2~O(9SBcraCmcZ0}dc5$rEJ!v9Pbl&6ubxH@S& ztYob|2_`2;c^Oa>H*AXv!H4p7jIMDi7;0~m>)a$fmh^tqSUKkGutJV0J%@winXVE} z1%Efz)uZZ}4@jH2eb^k(9K)`8{RrURx2bPm4BcAoetOQG1Yd9lGtN|#HSUjX16N>h zgp&z_RHqL2#CB%Ab+D{k$HbPfS>)o3Tge}(!1u2$?BrpEgXExq>_cGo??dcNzwR(V z`2az=)m9(}T9VsMQ)TcvTmoO*co=y?Ehmv68vM8`XAYc}We zjk&~={oCs$W&`ksP}g8;6e0#Qzfi1(I;sI<8?wAN#=S{q>b48Z8FtBqMe3Lo?t!EY z^itX@b~44Vwu5KIb~f1^NSYKTZoKLnZZe6uiSTR9JbuYG=>r+hd$|$O8?Z9?6eW!k zTvcHux%(;faiU}^r84lESQ4bMI=%MtQE>xOs(mCe>RrTGIvDfQnE0D5LQjK%wz@pq z{80dAMVzvl{BgUGwK)lIPb$1`LijJNSCwa+)WkhJcWqqlj9V`-C$fYU5EheRA zYafq_r_hB0^C}Z2UoB0XSs!8%AUq)yVUO) zwX6RI_&)zfJ?O}QN})B zszeLFN+26+QHH@RthaWS#8B>Gj$1KjY3qnj(efg95O48)}Hn;x28!H&jZ`_1+LeOo1{$L zw1a-o%V@mzgD3f2q79xeeEC1aKOyC7B61gS*S?_Zh`&^p>&?}@RO{q0!(DW^ec6;M zYT#36iu`t^u4YK394UnkPHrG6(vS#2#W7^a)DseTl(SK{_mRx$SSO(;R_bGn<;tZ{ z)`77$`ig8YMyqtHF!Oe^VW=Tk_L10)5Fg6Lmp5r4<(4)Vuimrx8er5B(n2pC(7r5? z#p<4o`2yc+!ZWADaFv&@35Yi_ve!%T@*JOz%$|SD0Vg&dWx_ie8OD<1#3l8(_F|Jo zCmXF1Uv%5xfF-Fk3?4k)4sbvl&!T!idJn0sbY#s!A+COh21I8hGu6fXK(MHhwc<^7 zjk#}tUy&wBpV8PzVY|f#+K#Y!YbCTm*g~AP zgs!E>RURoH8CYZ1E6;(H%K|7or+2N9^-bbqr-9b9nv)Xdd--LXSApu89O>+r&{j(e zsoCK3=YM5>U@;s1%m%t8n8Ez6Tl$-szkla^0A(mQvov>gGWtbU4d3`(1<+GX_por* zJEnKK!ZAfXWakj?oanK>w98Y9u$CH^O}GD3ny%d#s%lo*wAAtBn7P_V4@?f6B`EFdP27|nUbv{J6fxz z&di#|ozz#*%c7NKR-|Rr$zJ`G^W7UZb$KrG$#u0iQ!4Pom1;dBDrR`K5>p%fuIim| z)uO7-JkL@}EF$p2sMc%(@TkgyPCk7K`eakofj`y_h6>Tv{FFOv?|n8K1nWY~c$J7O zo$OnJ8VwVPt8`m#*V2+6*PL2&p-b36MazIZ^`hSGmUdct9ltF~lGm8yY_CPrcVPqF zbm=0sw{Pc%=v4NPkOWx#dk#Lxd4?Z0s9pr?U_k))RlmZg8}zO3szcme$P5m32;ToK?74f|_(j%4_CBhdvdOZ zAAS*wBz1AnzmDxfU@^OsTn#5a;%Jrku_al3e{

1bvi{DS7E@q1{$_8->K{_OWv2 zCZTgG2Pr3n8|ec9kIu&uC|d?k4-cQ4#}Z`qDX5Y2mhC(jR1Ms;UG4Ho$DE|+SeJ@{ zJQQhAXj|<)*t3KiOWTuh{Wd^mS{u{&ERV)OpZwiQ%#1->r9p zSK_^*U~=?ywH~4IUxb}{0J!SmL!z2Tzq_PpetoC^_az1JFg0=gMcQADuOP%3=H1hH zH_=dG(PD;d*037Ov5G1924U#Zns?~fs+eh1%-bWqa%ssm3=nio1r3J<4G0IBETtr? zycs~0JIOn;MecYG=~OQsYHIrf?~A5>_ob%8+uOrVA+VCJw}{lygrBBdY1k<8B^wf6 zl|<%N$7)fOZX$%y>4ueco_Gb1H@B%XrKVwrn6hUOecnc^PU0rFuCB5=*2;|u-`o(@ zL*tr4bnQzXYLc4XqFbv5sK0}A)`}`8iM8ehtj#Oc5DrE;0VxbPmL@BUa_BQwa$EW~sU#-LP0?sGmqfUGhGWcciGZ*4(}u3z=@b>Ow9DQe7lcO3K}BG3j(t& zH10>sK!&4Q5-=gN@Nxj6{|*nuyqw7KZJ1?p)NUJ?U0bOigGdsOk}Iz&9PmN_5=W*Z9M zy^pA`&dX0oo6?CSuhE~(pYbLuTPp1a1Fa@e3Lu&mmgd$;D}&g-i=D-{sv?J9kIr9r zrX&Z)aFGK^kNY{LxrotP0}k*;uN12i_2a_JJhKwh zBt{D-JRxC$8U+-`u1xD>gJ^H4lbW;7spI-=H506i=ncdK;xq*L6f7jVz$XGMg5aQk zHRJY&$@g}i_SP##iC?lR?ltnWUTT-UDlq(*BTQaYNkg zNG#sNoo{WmP+Vl}U~?+T?g25b$E-7iwhu=VVgw3JdFXm~ba+LC4p>CP3~rNTiNBl7 zL{RfLLepNPEtZj}yL_#R{(^MqIlG)c0Va}>U|9Pl&B_3tV;Ps{r)WqBznD7FcTlP4 z`JQe2DvGhmeeHGGX39zGyOOxZ3tq~Dft(BQ;mDXwwJi?sBtxo$Gf1SS2w*eQ0p&RVMNVi@d zY8v4J0(n}%6*Rw(g~l@sUuxpiJ*Y}7TzBQyU+>-qWm*InUeGt@)T9g^0J#z4){Lw* zT;69if~U9DXBR9fgVPlYy7aDhJU)gDC?_GHQtwa6QXNaah7-CzA|Fx-lH7d@N9>38 zX(F&fd3w7AkZ+ha8-gKfX%@_~<#HDs?kBg5zW>V3%Xw5jwPs6uni{7r zd`EfPYrA*SU;xDtm@E>5TrJKlg5o=h;NSXk)pt4K)GbpP0xkUg>2o|oG=`UnX7^Un zb&@8d6Fj1cBWW^c(K#Csc8xEBa4KfHY>8Lp^77-lhzgWr9kR9_p+g|-9r?VSv?qA%^1O;cqgke)%AqHlR$B{!Y1Mq zj|)Ecg?{_!>kGDAwGa7%cwSUb{BcayJihkv$}ql+yu=O}jVvAFdC{Hjh$4}u+$mx% z5V$sUiGCX%D3A>bKwY8HR)Gv*lisI4q^3vJ*nDwj|mtr!0r!~+Qoe2cw^jPCXkT7tI*01|w@ z&gPC`?O1w7hQ%=&bcHi7(fqhY3${~JepA7y@^aLwHpew^Yk$;R4v{ASHjXjXtaTc_ zuz5*nXB&PrcyWx#gQ%?HyxawmS+Wu(7ssvB1UMh!1$to&o(mv_f=9~!9@VsJCGxpu z`>g5Sp=xDhpsiCy^y>=fI0DON$&pb7o7^d{@@&hj3!6PUd=vA;G;#7&8ChamsE{`^ zY8pDra8Jntp62Ivi)Y`*XbpM60s06v@Rz^-g)TW_F@B!~y7!4AJ>37mAuz!(!C+xQ zSR61?u!{N|qHWOeR%$RXRL~vpN0SGri7-klNHEJuivbi=0qSbdV4&ghf4i|7?$>z( zI{qH?i}`~a7GyB6|8pZRq982+P*r1+m-t&(%U5#ZWFQd-(CXKLHeN@y(c z;wqq1hzE@q1b$GG0VQ_)`{MeylBlVfy%UHR=;Z98>T3M&;{0i?+0T-Bck?I)AUQrz zeF**_iGu$JlCpLnFv`D9?q6R51jKPM{Rd6!0FF#KP=O|b3iQX*TqXSjO?gXaXAmLr zU#g&%@+XpjVArlGkfaPKk^PUSnMLsjlK<9nH*zxl^V2-jGC$4+HGE%?F3%4|y9>HN z|FJgz*HW$VwU8$RNtuBf(2vdZhW3x;R6%eoJM(|2zvKebxCh$s5J-*fhZ75B_yeUs zFTrToFiB^SNH?gV2>l?G&h!UD>UP%uKh1L;Er59!q&NoZRe$VEf?5Ar^&iUad&2gQ z&WE`E%lTg=_3XQT@gJOjkAi-Hbbqrl{(pA<>_GH4O8+xI^=IAhS#v+$vmgOK=>C!~_xFg-pLM>6kUfy=zL|u~KkNJ< z$L?p*?;%(Ze6w%%M(zjE|4dH&5$)_}mG3z{KUQ6s!Y@_+kInPH;kAC&{T^5HKmqz@ z@+!aA{YNIy&r;uKTz=r6e6v>d-%9<%_4R!+-iN^8H#0N(rQbiu-u&}-|2`q@k1agM zdHkW_1&%VDD_|I;NpK*OZfAjAb z`Ttl8km0{|{F`kWKWltH$^Ech;G2y`{7&N^%H;d0$cGv7Z^oJNOSiwAFaP<=em}wX z<8AA6<}bbeZc_7S=ii6PALi)3nOXL)o&Uj%-OnQ52M&L%(%ZaWiu^(R{b!Bu2WJl< h$Zw`p^gE5e2}ml*LW4$nU|{5+pXG<~Ugg7I{||-5t(pJ; literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew.bat b/gradlew.bat index c4bdd3a..e509b2d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,93 +1,93 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/install-util.sh b/install-util.sh deleted file mode 100644 index 6868df0..0000000 --- a/install-util.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" -COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" -ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" - -mkdir -p "$SECRETS_DIR" - -prompt() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-}" - local value="" - - read -r -p "$prompt_text" value - if [[ -z "$value" ]]; then - value="$default_value" - fi - - printf -v "$var_name" '%s' "$value" -} - -yes_no() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-y}" - local response - - read -r -p "$prompt_text" response - response="${response:-$default_value}" - if [[ "$response" =~ ^[Yy]([Ee][Ss])?$ ]]; then - printf -v "$var_name" 'true' - else - printf -v "$var_name" 'false' - fi -} - diff --git a/install.sh b/install.sh deleted file mode 100644 index 1ac6736..0000000 --- a/install.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -source ./install-util.sh - -prompt client_port "MediaGarrd-Client host port [8081]: " "8081" -prompt pickup_interval "Client automatic pickup interval in ISO-8601 format [PT12H]: " "PT12H" -prompt server_ip "MediaGarrd-Server IP [192.168.1.10]: " "192.168.1.10" -prompt client_downloads_host "Client download host path [./data/client/downloads]: " "./data/client/downloads" -prompt client_state_host "Client state host path [./data/client]: " "./data/client" - -cat > "$ENV_FILE" < "$CLIENT_ENV_FILE" < "$COMPOSE_FILE" <> serverRejected(RestClientResponseException e) { + String message = null; + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + message = body == null ? null : body.error(); + } catch (RuntimeException ignored) { + } + String reason = message == null ? "MediaGarrd server responded with " + e.getStatusCode().value() : message; + LOGGER.warn("MediaGarrd server rejected request: {}", reason); + return error(e.getStatusCode(), reason); + } + + @ExceptionHandler(ResourceAccessException.class) + public ResponseEntity> serverUnreachable(ResourceAccessException e) { + 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"); + } + + @ExceptionHandler(ResponseStatusException.class) + public ResponseEntity> rejected(ResponseStatusException e) { + LOGGER.warn("Rejected request: {}", e.getReason()); + return error(e.getStatusCode(), e.getReason()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> unreadable(HttpMessageNotReadableException e) { + LOGGER.warn("Unreadable request body: {}", e.getMessage()); + return error(HttpStatus.BAD_REQUEST, "Request body is missing or malformed"); + } + + @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) + public ResponseEntity> failed(RuntimeException e) { + HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST : HttpStatus.INTERNAL_SERVER_ERROR; + if (status.is5xxServerError()) { + LOGGER.error("Request failed: {}", e.getMessage()); + } else { + LOGGER.warn("Rejected request: {}", e.getMessage()); + } + return error(status, e.getMessage()); + } + + private static ResponseEntity> error(HttpStatusCode status, String message) { + String fallback = status instanceof HttpStatus known ? known.getReasonPhrase() : "Request failed"; + return ResponseEntity.status(status).body(Map.of("error", Objects.requireNonNullElse(message, fallback))); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java new file mode 100644 index 0000000..87ea9ae --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -0,0 +1,147 @@ +package wellatleastitried.mediagarrdclient.api; + +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; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; +import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; +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.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; + +@RestController +@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; + + public ClientController( + ClientStateService stateService, + ServerDiscoveryService discoveryService, + ServerApiService serverApiService, + BackupPickupService pickupService + ) { + this.stateService = stateService; + this.discoveryService = discoveryService; + this.serverApiService = serverApiService; + this.pickupService = pickupService; + } + + @GetMapping("/status") + public ClientStatusDto status() { + discoveryService.connectPreferredServer(); + return currentStatus(); + } + + @PostMapping("/discover") + public List discover() { + List discovered = discoveryService.discover(); + stateService.updateKnownServers(discovered); + 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())) { + stateService.setActiveServer(normalizeServerUrl(request.serverUrl())); + return currentStatus(); + } + if (isBlank(request.serverIp())) { + throw new IllegalArgumentException("Either serverUrl or serverIp must be provided"); + } + Integer port = request.serverPort(); + if (port != null && (port < 1 || port > 65535)) { + throw new IllegalArgumentException("serverPort must be between 1 and 65535"); + } + String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) + .orElseThrow(() -> new IllegalArgumentException("No MediaGarrd server found at " + request.serverIp().trim())); + stateService.setActiveServer(resolved); + return currentStatus(); + } + + @GetMapping("/backups") + public List listBackups() { + return serverApiService.listBackups(stateService.requireActiveServer()); + } + + @PostMapping("/backups/run") + public void runBackup() { + serverApiService.triggerBackup(stateService.requireActiveServer()); + } + + @PostMapping("/pickup") + public PickupStartDto pickupLatest() { + return pickupService.startPickupLatestTask(); + } + + @PostMapping("/pickup/{id}") + public PickupStartDto pickupById(@PathVariable String id) { + return pickupService.startPickupByIdTask(id); + } + + @GetMapping("/pickup/progress/{taskId}") + public PickupProgressDto pickupProgress(@PathVariable String taskId) { + return pickupService.pickupProgress(taskId); + } + + @PutMapping("/pickup-interval") + public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { + pickupService.updatePickupInterval(request.interval()); + return currentStatus(); + } + + private ClientStatusDto currentStatus() { + return new ClientStatusDto(stateService.getActiveServer(), stateService.getPickupInterval(), stateService.getKnownServers()); + } + + static String normalizeServerUrl(String serverUrl) { + String trimmed = serverUrl.trim().replaceAll("/+$", ""); + try { + URI uri = URI.create(trimmed); + if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && !isBlank(uri.getHost())) { + return trimmed; + } + } catch (IllegalArgumentException ignored) { + } + throw new IllegalArgumentException("serverUrl must be an http:// or https:// URL: " + serverUrl); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java new file mode 100644 index 0000000..6b83040 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java @@ -0,0 +1,21 @@ +package wellatleastitried.mediagarrdclient.api; + +public enum Endpoints { + + SERVER_HEALTH("/api/v1/health"), + 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"); + + private final String path; + + Endpoints(String path) { + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java new file mode 100644 index 0000000..642ca4d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java @@ -0,0 +1,86 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@RestController +@RequestMapping("/api/client") +public class ServerConfigController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerConfigController.class); + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + + public ServerConfigController(ClientStateService stateService, ServerApiService serverApiService) { + this.stateService = stateService; + this.serverApiService = serverApiService; + } + + @GetMapping("/server-config") + public ServerConfigDto serverConfig() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("GET /api/client/server-config, forwarding to {}", activeServer); + return serverApiService.serverConfig(activeServer); + } + + @PutMapping("/server-config") + public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/server-config, request={}, target={}", request, activeServer); + ServerConfigDto config = serverApiService.updateServerConfig(activeServer, request.backupLocation(), request.retentionCount()); + if (request.backupInterval() == null) { + return config; + } + ServerStatusDto status = serverApiService.updateServerSchedule(activeServer, request.backupInterval()); + return new ServerConfigDto(config.backupLocation(), config.retentionCount(), status.backupInterval()); + } + + @GetMapping("/services") + public List services() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("GET /api/client/services, forwarding to {}", activeServer); + return serverApiService.listServices(activeServer); + } + + @PostMapping("/services") + @ResponseStatus(HttpStatus.CREATED) + public ServiceDto addService(@RequestBody ServiceDto service) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("POST /api/client/services, name={}, target={}", service.name(), activeServer); + return serverApiService.addService(activeServer, service); + } + + @PutMapping("/services/{name}") + public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceDto service) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/services/{}, name={}, target={}", name, service.name(), activeServer); + return serverApiService.updateService(activeServer, name, service); + } + + @DeleteMapping("/services/{name}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void removeService(@PathVariable String name) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("DELETE /api/client/services/{}, target={}", name, activeServer); + serverApiService.removeService(activeServer, name); + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java new file mode 100644 index 0000000..0d0b8fe --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Duration; + +public record ServerConfigDto(String backupLocation, Integer retentionCount, Duration backupInterval) { +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java new file mode 100644 index 0000000..fdaf639 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.util.List; + +public record ServiceDto(String name, List paths) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java new file mode 100644 index 0000000..cee0e67 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java @@ -0,0 +1,275 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +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.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +@Service +public class BackupPickupService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); + private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; + private static final String ZIP_SUFFIX = ".zip"; + static final Duration FINISHED_TASK_RETENTION = Duration.ofMinutes(10); + + private enum PickupStatus { QUEUED, RUNNING, COMPLETED, FAILED } + + private final class PickupTask { + private final String taskId = UUID.randomUUID().toString(); + private final BackupDto backup; + private volatile PickupStatus status = PickupStatus.QUEUED; + private volatile long bytesWritten; + private volatile long totalBytes; + private volatile Path savedPath; + private volatile String error; + private volatile Instant finishedAt; + + private PickupTask(BackupDto backup) { + this.backup = backup; + this.totalBytes = backup.sizeBytes(); + } + + private boolean finished() { + return finishedAt != null; + } + + private void complete(Path path) { + savedPath = path; + bytesWritten = Math.max(bytesWritten, totalBytes); + totalBytes = Math.max(totalBytes, bytesWritten); + status = PickupStatus.COMPLETED; + finishedAt = clock.instant(); + } + + private void fail(String message) { + error = message; + status = PickupStatus.FAILED; + finishedAt = clock.instant(); + } + + private PickupStartDto started() { + return new PickupStartDto(taskId, backup.id(), backup.fileName(), totalBytes); + } + + private PickupProgressDto progress() { + return new PickupProgressDto(taskId, status.name(), backup.id(), backup.fileName(), bytesWritten, totalBytes, + savedPath == null ? null : savedPath.toString(), error); + } + } + + private final Configuration configuration; + private final ClientStateService clientStateService; + private final ServerApiService serverApiService; + private final Clock clock; + private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final Map tasks = new LinkedHashMap<>(); + private volatile Instant nextPickup; + + @Autowired + public BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService) { + this(configuration, clientStateService, serverApiService, Clock.systemUTC()); + } + + BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { + this.configuration = configuration; + this.clientStateService = clientStateService; + this.serverApiService = serverApiService; + this.clock = clock; + this.nextPickup = clock.instant().plus(clientStateService.getPickupInterval()); + } + + @Scheduled(fixedDelay = 60_000) + public void scheduledPickup() { + Instant now = clock.instant(); + if (now.isBefore(nextPickup)) { + return; + } + nextPickup = now.plus(clientStateService.getPickupInterval()); + try { + LOGGER.info("Scheduled pickup saved {}, next pickup at {}", pickupLatestAuto(), nextPickup); + } catch (RuntimeException e) { + LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", nextPickup, e.getMessage()); + } + } + + public Duration updatePickupInterval(Duration interval) { + Duration updated = clientStateService.setPickupInterval(interval); + nextPickup = clock.instant().plus(updated); + return updated; + } + + public PickupStartDto startPickupLatestTask() { + String server = clientStateService.requireActiveServer(); + return startPickupTask(server, latest(serverApiService.listBackups(server))); + } + + public PickupStartDto startPickupByIdTask(String backupId) { + String server = clientStateService.requireActiveServer(); + BackupDto backup = serverApiService.listBackups(server).stream() + .filter(candidate -> candidate.id().equals(backupId)) + .findFirst() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup not found: " + backupId)); + return startPickupTask(server, backup); + } + + public synchronized PickupProgressDto pickupProgress(String taskId) { + PickupTask task = tasks.get(taskId); + if (task == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: " + taskId); + } + return task.progress(); + } + + private synchronized PickupStartDto startPickupTask(String server, BackupDto backup) { + evictFinishedTasks(); + PickupTask running = tasks.values().stream() + .filter(task -> !task.finished() && task.backup.id().equals(backup.id())) + .findFirst() + .orElse(null); + if (running != null) { + LOGGER.info("Backup {} is already being downloaded by task {}", backup.id(), running.taskId); + return running.started(); + } + + PickupTask task = new PickupTask(backup); + tasks.put(task.taskId, task); + Path downloads = downloadsDirectory(); + Path existing = existingCopy(downloads, backup); + if (existing != null) { + LOGGER.info("Backup {} is already downloaded at {}", backup.id(), existing); + task.complete(existing); + } else { + executor.submit(() -> download(server, inside(downloads, backup.fileName()), task)); + } + return task.started(); + } + + private void download(String server, Path destination, PickupTask task) { + task.status = PickupStatus.RUNNING; + try { + Path saved = serverApiService.downloadById(server, task.backup.id(), destination, (written, total) -> { + task.bytesWritten = written; + if (total > 0) { + task.totalBytes = total; + } + }); + task.complete(saved); + LOGGER.info("Pickup task {} saved {}", task.taskId, saved); + } catch (RuntimeException e) { + task.fail(e.getMessage()); + LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + } + } + + private void evictFinishedTasks() { + Instant cutoff = clock.instant().minus(FINISHED_TASK_RETENTION); + tasks.values().removeIf(task -> task.finished() && task.finishedAt.isBefore(cutoff)); + } + + private Path pickupLatestAuto() { + String server = clientStateService.requireActiveServer(); + List backups = serverApiService.listBackups(server); + BackupDto latest = latest(backups); + Path downloads = downloadsDirectory(); + Path existing = existingCopy(downloads, latest); + if (existing != null) { + LOGGER.info("Scheduled pickup skipped, backup {} is already downloaded at {}", latest.id(), existing); + return existing; + } + + Path downloaded = serverApiService.downloadById(server, latest.id(), inside(downloads, autoFileName(latest)), null); + deleteIfSameSize(inside(downloads, latest.fileName()), latest); + if (backups.size() > 1) { + deleteQuietly(inside(downloads, autoFileName(backups.get(1)))); + } + return downloaded; + } + + private Path existingCopy(Path downloads, BackupDto backup) { + return Stream.of(autoFileName(backup), backup.fileName()) + .map(name -> inside(downloads, name)) + .filter(path -> hasSize(path, backup.sizeBytes())) + .findFirst() + .orElse(null); + } + + private void deleteIfSameSize(Path path, BackupDto backup) { + if (hasSize(path, backup.sizeBytes())) { + deleteQuietly(path); + } + } + + private static boolean hasSize(Path path, long size) { + try { + return Files.isRegularFile(path) && Files.size(path) == size; + } catch (IOException e) { + LOGGER.warn("Could not inspect {}: {}", path, e.getMessage()); + return false; + } + } + + private static void deleteQuietly(Path path) { + try { + if (Files.deleteIfExists(path)) { + LOGGER.info("Removed superseded download {}", path.getFileName()); + } + } catch (IOException e) { + LOGGER.warn("Could not remove {}: {}", path, e.getMessage()); + } + } + + private static BackupDto latest(List backups) { + if (backups.isEmpty()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No backups found on server"); + } + return backups.getFirst(); + } + + private static String autoFileName(BackupDto backup) { + String name = backup.fileName(); + return name.endsWith(ZIP_SUFFIX) + ? name.substring(0, name.length() - ZIP_SUFFIX.length()) + AUTO_DOWNLOAD_SUFFIX + ZIP_SUFFIX + : name + AUTO_DOWNLOAD_SUFFIX; + } + + private static Path inside(Path downloads, String fileName) { + Path path = downloads.resolve(fileName).normalize(); + if (!downloads.equals(path.getParent())) { + throw new IllegalArgumentException("Backup file name must not leave the download directory: " + fileName); + } + return path; + } + + private Path downloadsDirectory() { + return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java new file mode 100644 index 0000000..258c718 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -0,0 +1,137 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.Configuration; + +@Service +public class ClientStateService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); + private static final Duration DEFAULT_PICKUP_INTERVAL = Duration.ofHours(12); + + @JsonIgnoreProperties(ignoreUnknown = true) + record ClientState(String activeServer, long pickupIntervalSeconds, List knownServers) { + } + + private final Path statePath; + private final ObjectMapper mapper; + private final Set knownServers = new LinkedHashSet<>(); + private String activeServer; + private Duration pickupInterval; + + public ClientStateService(Configuration configuration, ObjectMapper mapper) { + this.statePath = Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); + this.mapper = mapper; + this.pickupInterval = valid(configuration.getPickupInterval()) ? configuration.getPickupInterval() : DEFAULT_PICKUP_INTERVAL; + load(); + LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}", activeServer, pickupInterval, knownServers); + } + + public synchronized String getActiveServer() { + return activeServer; + } + + public synchronized String requireActiveServer() { + if (isBlank(activeServer)) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); + } + return activeServer; + } + + public synchronized Duration getPickupInterval() { + return pickupInterval; + } + + 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); + } + 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); + } + save(); + } + + public synchronized Duration setPickupInterval(Duration interval) { + if (!valid(interval)) { + throw new IllegalArgumentException("Pickup interval must be a positive duration"); + } + pickupInterval = interval; + LOGGER.info("Pickup interval updated to {}", interval); + save(); + return interval; + } + + private void load() { + if (!Files.exists(statePath)) { + LOGGER.info("No state file at {}, starting fresh", statePath); + return; + } + try { + ClientState state = mapper.readValue(statePath.toFile(), ClientState.class); + if (state.knownServers() != null) { + knownServers.addAll(state.knownServers()); + } + activeServer = isBlank(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : state.activeServer(); + Duration saved = Duration.ofSeconds(state.pickupIntervalSeconds()); + if (valid(saved)) { + pickupInterval = saved; + } + } catch (IOException e) { + LOGGER.warn("Could not read state from {}, starting with defaults: {}", statePath, e.getMessage()); + } + } + + private void save() { + try { + Files.createDirectories(statePath.getParent()); + Path temp = statePath.resolveSibling(statePath.getFileName() + ".tmp"); + ClientState state = new ClientState(activeServer == null ? "" : activeServer, pickupInterval.toSeconds(), new ArrayList<>(knownServers)); + mapper.writerWithDefaultPrettyPrinter().writeValue(temp.toFile(), state); + Files.move(temp, statePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + throw new IllegalStateException("Failed to save client state to " + statePath, e); + } + } + + private static boolean valid(Duration duration) { + return duration != null && duration.isPositive(); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java new file mode 100644 index 0000000..f6db95b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -0,0 +1,224 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +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.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.RestClient; +import org.springframework.web.util.UriUtils; + +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; + +@Service +public class ServerApiService { + + @FunctionalInterface + public interface DownloadProgressListener { + void onProgress(long bytesWritten, long totalBytes); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); + private static final String SERVICE_PATH = Endpoints.SERVER_SERVICES.getPath() + "/{name}"; + 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); + private static final int BUFFER_SIZE = 64 * 1024; + + private final HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + private final RestClient healthClient = restClient(HEALTH_TIMEOUT); + private final RestClient restClient = restClient(REQUEST_TIMEOUT); + private final RestClient backupRunClient = restClient(null); + + private RestClient restClient(Duration readTimeout) { + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + if (readTimeout != null) { + requestFactory.setReadTimeout(readTimeout); + } + return RestClient.builder().requestFactory(requestFactory).build(); + } + + public ServerStatusDto health(String serverUrl) { + ServerStatusDto status = healthClient.get() + .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) + .retrieve() + .body(ServerStatusDto.class); + LOGGER.debug("Server health of {}: {}", serverUrl, status); + return status; + } + + public List listBackups(String serverUrl) { + List backups = restClient.get() + .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) + .retrieve() + .body(new ParameterizedTypeReference<>() {}); + LOGGER.debug("Received {} backup(s) from {}", backups == null ? 0 : backups.size(), serverUrl); + return backups == null ? List.of() : backups; + } + + public void triggerBackup(String serverUrl) { + LOGGER.info("Triggering backup on {}", serverUrl); + backupRunClient.post() + .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) + .retrieve() + .toBodilessEntity(); + LOGGER.info("Backup finished on {}", serverUrl); + } + + public ServerStatusDto updateServerSchedule(String serverUrl, Duration interval) { + LOGGER.info("Updating server schedule on {} to {}", serverUrl, interval); + return restClient.put() + .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("backupInterval", interval.toString())) + .retrieve() + .body(ServerStatusDto.class); + } + + public ServerConfigDto serverConfig(String serverUrl) { + return restClient.get() + .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) + .retrieve() + .body(ServerConfigDto.class); + } + + public ServerConfigDto updateServerConfig(String serverUrl, String backupLocation, Integer retentionCount) { + LOGGER.info("Updating server configuration on {}: backupLocation={}, retentionCount={}", serverUrl, backupLocation, retentionCount); + Map body = new HashMap<>(); + body.put("backupLocation", backupLocation); + body.put("retentionCount", retentionCount); + return restClient.put() + .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body) + .retrieve() + .body(ServerConfigDto.class); + } + + public List listServices(String serverUrl) { + List services = restClient.get() + .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) + .retrieve() + .body(new ParameterizedTypeReference<>() {}); + return services == null ? List.of() : services; + } + + public ServiceDto addService(String serverUrl, ServiceDto service) { + LOGGER.info("Adding service {} on {}", service.name(), serverUrl); + return restClient.post() + .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(service) + .retrieve() + .body(ServiceDto.class); + } + + public ServiceDto updateService(String serverUrl, String name, ServiceDto service) { + LOGGER.info("Updating service {} on {}", name, serverUrl); + return restClient.put() + .uri(serverUrl + SERVICE_PATH, name) + .contentType(MediaType.APPLICATION_JSON) + .body(service) + .retrieve() + .body(ServiceDto.class); + } + + public void removeService(String serverUrl, String name) { + LOGGER.info("Removing service {} from {}", name, serverUrl); + restClient.delete() + .uri(serverUrl + SERVICE_PATH, name) + .retrieve() + .toBodilessEntity(); + } + + public Path downloadById(String serverUrl, String backupId, Path destination, DownloadProgressListener progressListener) { + URI uri = URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + UriUtils.encodePathSegment(backupId, StandardCharsets.UTF_8) + "/download"); + LOGGER.info("Downloading backup {} from {} to {}", backupId, serverUrl, destination); + Path temp = destination.resolveSibling(destination.getFileName() + ".part"); + try { + HttpResponse response = httpClient.send(HttpRequest.newBuilder(uri).GET().build(), HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() / 100 != 2) { + String snippet = new String(body.readNBytes(256), StandardCharsets.UTF_8); + LOGGER.error("Download of backup {} failed with HTTP {}: {}", backupId, response.statusCode(), snippet); + throw new IllegalStateException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); + } + Files.createDirectories(destination.getParent()); + long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); + copy(body, temp, totalBytes, progressListener); + } + if (!looksLikeZip(temp)) { + throw new IllegalStateException("Server returned non-zip content for backup " + backupId); + } + Files.move(temp, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + LOGGER.info("Downloaded backup {} to {} ({} bytes)", backupId, destination, Files.size(destination)); + return destination; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Download of backup " + backupId + " was interrupted", e); + } catch (IOException e) { + LOGGER.error("Failed to save backup {} to {}", backupId, destination, e); + throw new IllegalStateException("Failed to save backup " + backupId + ": " + e.getMessage(), e); + } finally { + deleteQuietly(temp); + } + } + + private static void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { + try (OutputStream out = Files.newOutputStream(target)) { + byte[] buffer = new byte[BUFFER_SIZE]; + long written = 0; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + written += read; + if (progressListener != null) { + progressListener.onProgress(written, totalBytes); + } + } + } + } + + private static boolean looksLikeZip(Path path) throws IOException { + byte[] header = new byte[4]; + try (InputStream in = Files.newInputStream(path)) { + if (in.readNBytes(header, 0, 4) < 4) { + return false; + } + } + return header[0] == 'P' && header[1] == 'K' + && ((header[2] == 3 && header[3] == 4) || (header[2] == 5 && header[3] == 6) || (header[2] == 7 && header[3] == 8)); + } + + private static void deleteQuietly(Path path) { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java new file mode 100644 index 0000000..ed9fbdd --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -0,0 +1,319 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.api.Endpoints; + +@Service +public class ServerDiscoveryService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); + + private static final List COMMON_PORTS = List.of(38471, 8080, 80); + private static final List VIRTUAL_INTERFACE_PREFIXES = List.of("docker", "br-", "veth", "virbr", "vmnet", "vboxnet", "cni", "flannel", "cali", "tun", "tap", "wg", "zt", "tailscale"); + private static final int MIN_SCAN_PREFIX_LENGTH = 24; + private static final int FIRST_UNPRIVILEGED_PORT = 1024; + private static final int MAX_PORT = 65535; + 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); + private static final Duration SCAN_DEADLINE = Duration.ofSeconds(20); + + enum Probe { OPEN, REFUSED, UNREACHABLE } + + record Candidate(String host, InetAddress address, int port) { + String url() { + return "http://" + (host.contains(":") ? "[" + host + "]" : host) + ":" + port; + } + } + + record HostInput(String host, Integer port) { + } + + private record ProbeResult(Probe probe, String server) { + } + + private record QuickResult(Optional server, boolean hostAlive) { + } + + private final Configuration configuration; + private final ClientStateService stateService; + private final ObjectMapper mapper; + private final HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES); + + public ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper) { + this.configuration = configuration; + this.stateService = stateService; + this.mapper = mapper; + } + + @Scheduled(fixedDelay = 30_000) + public void connectPreferredServer() { + String active = stateService.getActiveServer(); + if (active == null || active.isBlank()) { + resolvePreferredServer().ifPresent(stateService::setActiveServer); + } + } + + public List discover() { + long start = System.nanoTime(); + Set discovered = new LinkedHashSet<>(); + resolvePreferredServer().ifPresent(discovered::add); + + List hosts = localSubnetHosts(); + List ports = quickPorts(null); + List candidates = hosts.stream() + .flatMap(host -> ports.stream().map(port -> new Candidate(host.getHostAddress(), host, port))) + .toList(); + LOGGER.info("Scanning {} host(s) on ports {} ({} candidates)", hosts.size(), ports, candidates.size()); + discovered.addAll(findServers(candidates, deadline())); + + LOGGER.info("Network discovery found {} server(s) in {} ms: {}", discovered.size(), elapsedMillis(start), discovered); + return List.copyOf(discovered); + } + + public Optional resolvePreferredServer() { + String preferred = configuration.getPreferredServerIp(); + if (preferred == null || preferred.isBlank()) { + return Optional.empty(); + } + HostInput input = parseHost(preferred); + InetAddress address = input == null ? null : resolve(input.host()); + return address == null ? Optional.empty() : quickResolve(input.host(), address, input.port(), deadline()).server(); + } + + public Optional resolveServerByIp(String input, Integer port) { + HostInput parsed = parseHost(input); + InetAddress address = parsed == null ? null : resolve(parsed.host()); + if (address == null) { + LOGGER.warn("Cannot resolve a server from '{}'", input); + return Optional.empty(); + } + Integer preferredPort = port != null ? port : parsed.port(); + long deadline = deadline(); + QuickResult quick = quickResolve(parsed.host(), address, preferredPort, deadline); + if (quick.server().isPresent() || !quick.hostAlive()) { + return quick.server(); + } + + LOGGER.info("No MediaGarrd server on the common ports of {}, scanning ports {}-{}", parsed.host(), FIRST_UNPRIVILEGED_PORT, MAX_PORT); + long start = System.nanoTime(); + Set probed = Set.copyOf(quickPorts(preferredPort)); + List candidates = IntStream.rangeClosed(FIRST_UNPRIVILEGED_PORT, MAX_PORT) + .filter(candidatePort -> !probed.contains(candidatePort)) + .mapToObj(candidatePort -> new Candidate(parsed.host(), address, candidatePort)) + .toList(); + Optional found = findServers(candidates, deadline).stream().findFirst(); + LOGGER.info("Port scan of {} finished in {} ms: {}", parsed.host(), elapsedMillis(start), found.orElse("no server found")); + return found; + } + + private QuickResult quickResolve(String host, InetAddress address, Integer preferredPort, long deadline) { + List> probes = quickPorts(preferredPort).stream() + .map(port -> probeAsync(new Candidate(host, address, port), deadline)) + .toList(); + List results = probes.stream().map(CompletableFuture::join).toList(); + Optional server = results.stream().map(ProbeResult::server).filter(Objects::nonNull).findFirst(); + boolean alive = results.stream().anyMatch(result -> result.probe() != Probe.UNREACHABLE); + server.ifPresentOrElse( + url -> LOGGER.info("Resolved MediaGarrd server at {}", url), + () -> LOGGER.debug("No MediaGarrd server on the common ports of {} (host {})", host, alive ? "reachable" : "unreachable")); + return new QuickResult(server, alive); + } + + private List findServers(List candidates, long deadline) { + List> probes = candidates.stream().map(candidate -> probeAsync(candidate, deadline)).toList(); + return probes.stream() + .map(CompletableFuture::join) + .map(ProbeResult::server) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private CompletableFuture probeAsync(Candidate candidate, long deadline) { + return CompletableFuture.supplyAsync(() -> { + Probe probe = connect(candidate, deadline); + return new ProbeResult(probe, probe == Probe.OPEN && isMediaGarrdServer(candidate) ? candidate.url() : null); + }, executor); + } + + private Probe connect(Candidate candidate, long deadline) { + try { + probeSlots.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return Probe.UNREACHABLE; + } + try (Socket socket = new Socket()) { + if (System.nanoTime() > deadline) { + return Probe.UNREACHABLE; + } + socket.connect(new InetSocketAddress(candidate.address(), candidate.port()), (int) CONNECT_TIMEOUT.toMillis()); + return Probe.OPEN; + } catch (ConnectException e) { + return e.getMessage() != null && e.getMessage().contains("refused") ? Probe.REFUSED : Probe.UNREACHABLE; + } catch (IOException | IllegalArgumentException e) { + return Probe.UNREACHABLE; + } finally { + probeSlots.release(); + } + } + + boolean isMediaGarrdServer(Candidate candidate) { + HttpRequest request = HttpRequest.newBuilder(URI.create(candidate.url() + Endpoints.SERVER_HEALTH.getPath())) + .timeout(HEALTH_TIMEOUT) + .GET() + .build(); + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + return false; + } + JsonNode health = mapper.readTree(response.body()); + return health.path("healthy").isBoolean() && health.has("backupInterval"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException | IllegalArgumentException e) { + LOGGER.debug("{} is not a MediaGarrd server: {}", candidate.url(), e.getMessage()); + return false; + } + } + + private List quickPorts(Integer preferredPort) { + return Stream.concat(Stream.of(preferredPort, configuration.getServerPort()), COMMON_PORTS.stream()) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private List localSubnetHosts() { + Set hosts = new LinkedHashSet<>(); + try { + for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) { + if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual() || isVirtualBridge(networkInterface)) { + continue; + } + for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { + if (address.getAddress() instanceof Inet4Address ipv4) { + hosts.addAll(subnetHosts(ipv4, address.getNetworkPrefixLength())); + } + } + } + } catch (SocketException e) { + LOGGER.warn("Could not list network interfaces: {}", e.getMessage()); + } + return List.copyOf(hosts); + } + + static List subnetHosts(Inet4Address address, int prefixLength) { + int prefix = Math.min(Math.max(prefixLength, MIN_SCAN_PREFIX_LENGTH), 30); + int ip = toInt(address.getAddress()); + int mask = -1 << (32 - prefix); + int network = ip & mask; + int broadcast = network | ~mask; + List hosts = new ArrayList<>(broadcast - network - 1); + for (int host = network + 1; host < broadcast; host++) { + hosts.add(toAddress(host)); + } + return hosts; + } + + private static boolean isVirtualBridge(NetworkInterface networkInterface) { + String name = networkInterface.getName(); + return VIRTUAL_INTERFACE_PREFIXES.stream().anyMatch(name::startsWith); + } + + static HostInput parseHost(String input) { + if (input == null || input.isBlank()) { + return null; + } + String trimmed = input.trim(); + try { + URI uri = URI.create(trimmed.contains("://") ? trimmed : "http://" + trimmed); + if (uri.getHost() == null || uri.getHost().isBlank()) { + return null; + } + String host = uri.getHost().startsWith("[") ? uri.getHost().substring(1, uri.getHost().length() - 1) : uri.getHost(); + return new HostInput(host, uri.getPort() > 0 ? uri.getPort() : null); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static int toInt(byte[] bytes) { + return (bytes[0] & 0xFF) << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF); + } + + private static InetAddress toAddress(int ip) { + try { + return InetAddress.getByAddress(new byte[] {(byte) (ip >>> 24), (byte) (ip >>> 16), (byte) (ip >>> 8), (byte) ip}); + } catch (UnknownHostException e) { + throw new IllegalStateException(e); + } + } + + private static InetAddress resolve(String host) { + try { + return InetAddress.getByName(host); + } catch (UnknownHostException e) { + LOGGER.debug("Cannot resolve host {}: {}", host, e.getMessage()); + return null; + } + } + + private static long deadline() { + return System.nanoTime() + SCAN_DEADLINE.toNanos(); + } + + private static long elapsedMillis(long start) { + return Duration.ofNanos(System.nanoTime() - start).toMillis(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java b/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java deleted file mode 100644 index dabc55a..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdclient; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/css/**", "/js/**", "/images/**", "/*.png", "/*.ico", "/*.svg") - .addResourceLocations("classpath:/static/") - .setCachePeriod(0); - - registry - .addResourceHandler("/index.html") - .addResourceLocations("classpath:/static/index.html") - .setCachePeriod(0); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java b/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java deleted file mode 100644 index e3fe178..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java +++ /dev/null @@ -1,216 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import java.time.Duration; -import java.util.List; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; -import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; -import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; -import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@RestController -@RequestMapping("/api/client") -public class ClientController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class); - - private final Configuration configuration; - private final ClientStateService stateService; - private final ServerDiscoveryService discoveryService; - private final ServerApiService serverApiService; - private final BackupPickupService pickupService; - - public ClientController( - Configuration configuration, - ClientStateService stateService, - ServerDiscoveryService discoveryService, - ServerApiService serverApiService, - BackupPickupService pickupService - ) { - this.configuration = configuration; - this.stateService = stateService; - this.discoveryService = discoveryService; - this.serverApiService = serverApiService; - this.pickupService = pickupService; - } - - @GetMapping("/status") - public ClientStatusDto status() { - LOGGER.info("GET /api/client/status"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - String preferredIp = configuration.getPreferredServerIp(); - if (preferredIp != null && !preferredIp.isBlank()) { - LOGGER.info("No active server, probing preferred IP: {}", preferredIp); - discoveryService.resolveServerByIp(preferredIp).ifPresent(url -> { - LOGGER.info("Auto-resolved server from preferred IP: {}", url); - stateService.setActiveServer(url); - }); - } - } - - ClientStatusDto dto = new ClientStatusDto( - stateService.getActiveServer(), - stateService.getPickupInterval(), - stateService.getKnownServers() - ); - LOGGER.info("Status: activeServer={}, pickupInterval={}, knownServers={}", dto.activeServer(), dto.pickupInterval(), dto.knownServers()); - return dto; - } - - @PostMapping("/discover") - public ClientStatusDto discover() { - LOGGER.info("POST /api/client/discover, starting network scan"); - List discovered = discoveryService.discover(); - LOGGER.info("Discovery complete, found {} server(s): {}", discovered.size(), discovered); - stateService.updateKnownServers(discovered); - return status(); - } - - @GetMapping("/server-health") - public ConnectionStatusDto serverHealth() { - LOGGER.info("GET /api/client/server-health"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("server-health: no active server configured"); - return new ConnectionStatusDto("", false); - } - - try { - ServerStatusDto serverStatus = serverApiService.health(activeServer); - LOGGER.info("server-health: {} is reachable", activeServer); - return new ConnectionStatusDto(activeServer, true, serverStatus); - } catch (RuntimeException ex) { - LOGGER.warn("server-health: {} is unreachable: {}", activeServer, ex.getMessage()); - return new ConnectionStatusDto(activeServer, false); - } - } - - @PutMapping("/server") - public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { - LOGGER.info("PUT /api/client/server, request={}", request); - if (request == null) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Request body is required"); - } - - String requestedUrl = request.serverUrl(); - if (requestedUrl != null && !requestedUrl.isBlank()) { - LOGGER.info("Setting active server by URL: {}", requestedUrl.trim()); - stateService.setActiveServer(requestedUrl.trim()); - return status(); - } - - String serverIp = request.serverIp(); - if (serverIp == null || serverIp.isBlank()) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Either serverUrl or serverIp must be provided"); - } - - Integer serverPort = request.serverPort(); - if (serverPort != null && (serverPort < 1 || serverPort > 65535)) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "serverPort must be between 1 and 65535"); - } - - LOGGER.info("Resolving server by IP={}, port={}", serverIp, serverPort); - String resolved = discoveryService.resolveServerByIp(serverIp, serverPort) - .orElseThrow(() -> { - LOGGER.warn("Unable to resolve server at IP={}, port={}", serverIp, serverPort); - return new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unable to resolve MediaGarrd server on provided IP"); - }); - LOGGER.info("Resolved server: {}", resolved); - stateService.setActiveServer(resolved); - return status(); - } - - @GetMapping("/backups") - public List listBackups() { - String activeServer = requireActiveServer(); - LOGGER.info("GET /api/client/backups, forwarding to {}", activeServer); - List backups = serverApiService.listBackups(activeServer); - LOGGER.info("Received {} backup(s) from server", backups.size()); - return backups; - } - - @PostMapping("/backups/run") - public void runBackup() { - String activeServer = requireActiveServer(); - LOGGER.info("POST /api/client/backups/run, triggering backup on {}", activeServer); - serverApiService.triggerBackup(activeServer); - LOGGER.info("Backup triggered successfully on {}", activeServer); - } - - @PostMapping("/pickup") - public PickupStartDto pickupNow() { - LOGGER.info("POST /api/client/pickup, manual pickup requested"); - PickupStartDto task = pickupService.startPickupLatestTask(); - LOGGER.info("Pickup task started: {}", task.taskId()); - return task; - } - - @PostMapping("/pickup/{id}") - public PickupStartDto pickupById(@PathVariable String id) { - LOGGER.info("POST /api/client/pickup/{}, manual pickup by id requested", id); - PickupStartDto task = pickupService.startPickupByIdTask(id); - LOGGER.info("Pickup-by-id task started: {} for {}", task.taskId(), id); - return task; - } - - @GetMapping("/pickup/progress/{taskId}") - public PickupProgressDto pickupProgress(@PathVariable String taskId) { - LOGGER.debug("GET /api/client/pickup/progress/{}", taskId); - PickupProgressDto progress = pickupService.pickupProgress(taskId); - LOGGER.debug("Pickup progress returned: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, progress.status(), progress.bytesWritten(), progress.totalBytes()); - return progress; - } - - @PutMapping("/pickup-interval") - public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { - LOGGER.info("PUT /api/client/pickup-interval, requested={}", request.interval()); - Duration duration = pickupService.updatePickupInterval(request.interval()); - LOGGER.info("Pickup interval updated to: {}", duration); - return new ClientStatusDto( - stateService.getActiveServer(), - duration, - stateService.getKnownServers() - ); - } - - @PutMapping("/server-schedule") - public void updateServerSchedule(@RequestBody IntervalUpdateRequest request) { - String activeServer = requireActiveServer(); - LOGGER.info("PUT /api/client/server-schedule, interval={}, target={}", request.interval(), activeServer); - serverApiService.updateServerSchedule(activeServer, request.interval()); - LOGGER.info("Server schedule updated on {}", activeServer); - } - - private String requireActiveServer() { - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("Request rejected: no active server configured"); - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); - } - return activeServer; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java deleted file mode 100644 index f4ca708..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java +++ /dev/null @@ -1,28 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -public enum Endpoints { - - CLIENT_STATUS("/api/client/status"), - CLIENT_DISCOVER("/api/client/discover"), - CLIENT_SERVER("/api/client/server"), - CLIENT_BACKUPS("/api/client/backups"), - CLIENT_BACKUP_RUN("/api/client/backups/run"), - CLIENT_PICKUP("/api/client/pickup"), - CLIENT_PICKUP_INTERVAL("/api/client/pickup-interval"), - CLIENT_SERVER_SCHEDULE("/api/client/server-schedule"), - SERVER_HEALTH("/api/v1/health"), - SERVER_BACKUPS("/api/v1/backups"), - SERVER_BACKUP_RUN("/api/v1/backups/run"), - SERVER_BACKUP_LATEST_DOWNLOAD("/api/v1/backups/latest/download"), - SERVER_SCHEDULE("/api/v1/schedule"); - - private final String path; - - Endpoints(String path) { - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java b/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java deleted file mode 100644 index 9a2eb36..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class WebController { - - @GetMapping("/") - public String index() { - return "forward:/index.html"; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java deleted file mode 100644 index 09dd29f..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java +++ /dev/null @@ -1,330 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import jakarta.annotation.PreDestroy; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; - -@Service -public class BackupPickupService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); - private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; - - private final Configuration configuration; - private final ClientStateService clientStateService; - private final ServerApiService serverApiService; - private final ExecutorService pickupExecutor = Executors.newCachedThreadPool(); - private final Map pickupTasks = new ConcurrentHashMap<>(); - private Instant nextPickup; - - private enum PickupStatus { - QUEUED, - RUNNING, - COMPLETED, - FAILED - } - - private static final class PickupTaskState { - private final String taskId; - private final String backupId; - private final String fileName; - private volatile PickupStatus status; - private volatile long bytesWritten; - private volatile long totalBytes; - private volatile Path savedPath; - private volatile String error; - - private PickupTaskState(String taskId, String backupId, String fileName, long totalBytes) { - this.taskId = taskId; - this.backupId = backupId; - this.fileName = fileName; - this.totalBytes = totalBytes; - this.status = PickupStatus.QUEUED; - this.bytesWritten = 0L; - } - } - - public BackupPickupService( - Configuration configuration, - ClientStateService clientStateService, - ServerApiService serverApiService - ) { - this.configuration = configuration; - this.clientStateService = clientStateService; - this.serverApiService = serverApiService; - this.nextPickup = Instant.now().plus(clientStateService.getPickupInterval()); - } - - @Scheduled(fixedDelay = 60000) - public void scheduledPickup() { - Instant now = Instant.now(); - if (now.isBefore(nextPickup)) { - return; - } - LOGGER.info("Scheduled pickup triggered, next scheduled check was {}", nextPickup); - try { - Path result = pickupLatestAuto(); - LOGGER.info("Scheduled pickup complete: {}", result); - } catch (RuntimeException ex) { - LOGGER.warn("Scheduled pickup failed", ex); - } - nextPickup = now.plus(clientStateService.getPickupInterval()); - LOGGER.info("Next pickup scheduled at: {}", nextPickup); - } - - public Path pickupLatest() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - return pickupManual(activeServer, latest); - } - - public PickupStartDto startPickupLatestTask() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - return startPickupTask(activeServer, latest); - } - - public PickupStartDto startPickupByIdTask(String backupId) { - String activeServer = requireActiveServer(); - return startPickupTask(activeServer, requireBackup(activeServer, backupId)); - } - - public PickupProgressDto pickupProgress(String taskId) { - PickupTaskState state = pickupTasks.get(taskId); - if (state == null) { - LOGGER.warn("Pickup task not found: {}", taskId); - throw new IllegalStateException("Pickup task not found: " + taskId); - } - - LOGGER.debug("Pickup task status requested: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, state.status, state.bytesWritten, state.totalBytes); - - return new PickupProgressDto( - state.taskId, - state.status.name(), - state.backupId, - state.fileName, - state.bytesWritten, - state.totalBytes, - state.savedPath == null ? null : state.savedPath.toString(), - state.error - ); - } - - public Path pickupById(String backupId) { - String activeServer = requireActiveServer(); - return pickupManual(activeServer, requireBackup(activeServer, backupId)); - } - - private Path pickupLatestAuto() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, latest); - if (existingPath != null) { - LOGGER.info("Auto pickup skipped for {} because local copy already exists at {}", latest.id(), existingPath); - return existingPath; - } - - Path latestAutoPath = downloadsDir.resolve(withAutoSuffix(latest.fileName())); - LOGGER.info("Auto pickup downloading {} to {}", latest.fileName(), latestAutoPath); - Path downloaded = serverApiService.downloadById(activeServer, latest.id(), latestAutoPath); - deletePlainDuplicate(downloadsDir, latest); - - if (backups.size() > 1) { - BackupDto secondMostRecent = backups.get(1); - Path secondAutoPath = downloadsDir.resolve(withAutoSuffix(secondMostRecent.fileName())); - if (Files.exists(secondAutoPath)) { - try { - Files.deleteIfExists(secondAutoPath); - LOGGER.info("Auto pickup removed second-most-recent auto-downloaded backup {}", secondAutoPath.getFileName()); - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to remove second-most-recent auto-downloaded backup {}", secondAutoPath, e); - } - } - } - - return downloaded; - } - - private Path findExistingCopy(Path downloadsDir, BackupDto backup) { - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - if (matchesBackup(autoPath, backup)) { - return autoPath; - } - - Path plainPath = downloadsDir.resolve(backup.fileName()); - if (matchesBackup(plainPath, backup)) { - return plainPath; - } - - return null; - } - - private boolean matchesBackup(Path candidate, BackupDto backup) { - if (!Files.exists(candidate)) { - return false; - } - - try { - return Files.size(candidate) == backup.sizeBytes(); - } catch (IOException e) { - LOGGER.warn("Failed to inspect local file {} for backup {}", candidate, backup.id(), e); - return false; - } - } - - private void deletePlainDuplicate(Path downloadsDir, BackupDto backup) { - Path plainPath = downloadsDir.resolve(backup.fileName()); - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - - if (!Files.exists(autoPath) || !Files.exists(plainPath)) { - return; - } - - try { - long autoSize = Files.size(autoPath); - long plainSize = Files.size(plainPath); - if (autoSize == backup.sizeBytes() && plainSize == backup.sizeBytes()) { - Files.deleteIfExists(plainPath); - LOGGER.info("Auto pickup removed plain duplicate for backup {} and kept {}", backup.id(), autoPath.getFileName()); - } - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to reconcile plain duplicate for backup {}", backup.id(), e); - } - } - - private PickupStartDto startPickupTask(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - String taskId = UUID.randomUUID().toString(); - PickupTaskState existingState = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - existingState.status = PickupStatus.COMPLETED; - existingState.bytesWritten = backup.sizeBytes(); - existingState.savedPath = existingPath; - pickupTasks.put(taskId, existingState); - LOGGER.info("Pickup task {} reused existing local copy for backup {} at {}", taskId, backup.id(), existingPath); - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - Path destination = downloadsDir.resolve(backup.fileName()); - String taskId = UUID.randomUUID().toString(); - PickupTaskState state = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - pickupTasks.put(taskId, state); - - LOGGER.info("Starting pickup task {} for backup {} to {}", taskId, backup.id(), destination); - pickupExecutor.submit(() -> runPickupTask(activeServer, backup, destination, state)); - - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - private Path pickupManual(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - LOGGER.info("Manual pickup: skipping {} because client already has a local copy at {}", backup.id(), existingPath); - return existingPath; - } - - Path destination = downloadsDir.resolve(backup.fileName()); - LOGGER.info("Manual pickup: downloading {} to {}", backup.fileName(), destination); - return serverApiService.downloadById(activeServer, backup.id(), destination); - } - - private void runPickupTask(String activeServer, BackupDto backup, Path destination, PickupTaskState state) { - state.status = PickupStatus.RUNNING; - try { - Path downloaded = serverApiService.downloadById( - activeServer, - backup.id(), - destination, - (bytesWritten, totalBytes) -> { - state.bytesWritten = bytesWritten; - if (totalBytes > 0) { - state.totalBytes = totalBytes; - } - } - ); - state.savedPath = downloaded; - if (state.totalBytes <= 0) { - state.totalBytes = state.bytesWritten; - } - state.status = PickupStatus.COMPLETED; - LOGGER.info("Pickup task {} completed: {}", state.taskId, downloaded); - } catch (RuntimeException ex) { - state.status = PickupStatus.FAILED; - state.error = ex.getMessage(); - LOGGER.warn("Pickup task {} failed for backup {}", state.taskId, backup.id(), ex); - } - } - - private BackupDto requireBackup(String activeServer, String backupId) { - return serverApiService.listBackups(activeServer).stream() - .filter(backup -> backup.id().equals(backupId)) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Backup not found: " + backupId)); - } - - private String requireActiveServer() { - String activeServer = clientStateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.error("Pickup requested but no active server is configured"); - throw new IllegalStateException("No active server selected"); - } - return activeServer; - } - - private BackupDto latestRequired(List backups) { - if (backups == null || backups.isEmpty()) { - throw new IllegalStateException("No backups found on server"); - } - return backups.get(0); - } - - private Path downloadsDirectory() { - return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); - } - - private String withAutoSuffix(String fileName) { - if (fileName.endsWith(".zip")) { - return fileName.substring(0, fileName.length() - 4) + AUTO_DOWNLOAD_SUFFIX + ".zip"; - } - return fileName + AUTO_DOWNLOAD_SUFFIX; - } - - @PreDestroy - public void shutdownPickupExecutor() { - pickupExecutor.shutdownNow(); - } - - public Duration updatePickupInterval(Duration interval) { - Duration updated = clientStateService.setPickupInterval(interval); - nextPickup = Instant.now().plus(updated); - return updated; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java deleted file mode 100644 index 9919fcd..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java +++ /dev/null @@ -1,133 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ClientStateService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); - - @JsonIgnoreProperties(ignoreUnknown = true) - private static class ClientState { - public String activeServer = ""; - public long pickupIntervalSeconds = 43_200; - public List knownServers = new ArrayList<>(); - } - - private final Configuration configuration; - private final ObjectMapper mapper; - private final List knownServers = new ArrayList<>(); - private String activeServer; - private Duration pickupInterval; - - public ClientStateService(Configuration configuration, ObjectMapper mapper) { - this.configuration = configuration; - this.mapper = mapper; - this.pickupInterval = safe(configuration.getPickupInterval()); - this.activeServer = null; - load(); - LOGGER.info("ClientStateService initialized: activeServer={}, pickupInterval={}, knownServers={}", - activeServer, pickupInterval, knownServers); - } - - public synchronized String getActiveServer() { - return activeServer; - } - - public synchronized Duration getPickupInterval() { - return pickupInterval; - } - - public synchronized List getKnownServers() { - return List.copyOf(knownServers); - } - - public synchronized void updateKnownServers(List servers) { - knownServers.clear(); - knownServers.addAll(servers.stream().distinct().toList()); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - LOGGER.info("Auto-selected first known server: {}", activeServer); - } - LOGGER.info("Known servers updated: {}", knownServers); - save(); - } - - public synchronized void setActiveServer(String serverUrl) { - LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); - this.activeServer = serverUrl; - if (serverUrl != null && !serverUrl.isBlank() && !knownServers.contains(serverUrl)) { - knownServers.add(serverUrl); - } - save(); - } - - public synchronized Duration setPickupInterval(Duration interval) { - this.pickupInterval = safe(interval); - LOGGER.info("Pickup interval updated to: {}", this.pickupInterval); - save(); - return this.pickupInterval; - } - - private void load() { - Path path = statePath(); - if (!Files.exists(path)) { - LOGGER.info("No state file found at {}, starting fresh", path); - return; - } - try { - ClientState state = mapper.readValue(path.toFile(), ClientState.class); - activeServer = state.activeServer; - pickupInterval = Duration.ofSeconds(state.pickupIntervalSeconds); - knownServers.clear(); - knownServers.addAll(state.knownServers); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - } - LOGGER.info("State loaded from {}: activeServer={}, pickupInterval={}, knownServers={}", - path, activeServer, pickupInterval, knownServers); - } catch (IOException e) { - LOGGER.warn("Failed to load state from {}, starting with defaults", path, e); - } - } - - private void save() { - Path path = statePath(); - try { - Files.createDirectories(path.getParent()); - ClientState state = new ClientState(); - state.activeServer = activeServer == null ? "" : activeServer; - state.pickupIntervalSeconds = pickupInterval.toSeconds(); - state.knownServers = List.copyOf(knownServers); - mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), state); - LOGGER.debug("Client state persisted to {}", path); - } catch (IOException e) { - throw new IllegalStateException("Failed to persist client state", e); - } - } - - private Path statePath() { - return Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); - } - - private Duration safe(Duration duration) { - if (duration == null || duration.isNegative() || duration.isZero()) { - return Duration.ofHours(12); - } - return duration; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java deleted file mode 100644 index 1c4628d..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java +++ /dev/null @@ -1,192 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Duration; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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.RestClient; - -import wellatleastitried.mediagarrdclient.api.Endpoints; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; - -@Service -public class ServerApiService { - - @FunctionalInterface - public interface DownloadProgressListener { - void onProgress(long bytesWritten, long totalBytes); - } - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); - - private final HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.ALWAYS) - .build(); - - private final RestClient restClient = RestClient.builder() - .requestFactory(new JdkClientHttpRequestFactory(httpClient)) - .build(); - - public ServerStatusDto health(String serverUrl) { - LOGGER.info("Probing server health: {}", serverUrl); - ServerStatusDto dto = restClient.get() - .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) - .retrieve() - .body(ServerStatusDto.class); - LOGGER.info("Server health OK: {}, running={}, interval={}", serverUrl, - dto != null ? dto.running() : "?", dto != null ? dto.backupInterval() : "?"); - return dto; - } - - public List listBackups(String serverUrl) { - LOGGER.info("Fetching backup list from: {}", serverUrl); - List response = restClient.get() - .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) - .retrieve() - .body(new ParameterizedTypeReference<>() {}); - List result = response == null ? List.of() : response; - LOGGER.info("Received {} backup(s) from {}", result.size(), serverUrl); - return result; - } - - public void triggerBackup(String serverUrl) { - LOGGER.info("Triggering backup on: {}", serverUrl); - restClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() - .toBodilessEntity(); - LOGGER.info("Backup trigger acknowledged by: {}", serverUrl); - } - - public void updateServerSchedule(String serverUrl, Duration interval) { - LOGGER.info("Updating server schedule on {} to interval={}", serverUrl, interval); - restClient.put() - .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) - .contentType(MediaType.APPLICATION_JSON) - .body("{\"backupInterval\":\"" + interval + "\"}") - .retrieve() - .toBodilessEntity(); - LOGGER.info("Server schedule update acknowledged by: {}", serverUrl); - } - - public Path downloadLatest(String serverUrl, Path destinationPath) { - return downloadLatest(serverUrl, destinationPath, null); - } - - public Path downloadLatest(String serverUrl, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading latest backup from {} to {}", serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUP_LATEST_DOWNLOAD.getPath()), - destinationPath, - "latest backup", - progressListener - ); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath) { - return downloadById(serverUrl, backupId, destinationPath, null); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading backup id={} from {} to {}", backupId, serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + backupId + "/download"), - destinationPath, - "backup " + backupId, - progressListener - ); - } - - private Path downloadFromUri(URI uri, Path destinationPath, String operationName, DownloadProgressListener progressListener) { - HttpRequest request = HttpRequest.newBuilder(uri).GET().build(); - - try { - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); - int status = response.statusCode(); - if (status < 200 || status >= 300) { - String snippet; - try (InputStream errorBody = response.body()) { - snippet = new String(errorBody.readNBytes(256)); - } - LOGGER.error("{} download failed from {} with HTTP {}: {}", operationName, uri, status, snippet); - throw new IllegalStateException(operationName + " download failed with HTTP " + status); - } - - Files.createDirectories(destinationPath.getParent()); - Path tempPath = destinationPath.resolveSibling(destinationPath.getFileName().toString() + ".tmp"); - long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); - - try (InputStream inputStream = response.body(); - OutputStream outputStream = Files.newOutputStream( - tempPath, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE - )) { - byte[] buffer = new byte[8192]; - long bytesWritten = 0L; - int read; - while ((read = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - bytesWritten += read; - if (progressListener != null) { - progressListener.onProgress(bytesWritten, totalBytes); - } - } - } - - if (!looksLikeZip(tempPath)) { - long size = Files.size(tempPath); - Files.deleteIfExists(tempPath); - LOGGER.error("{} download returned non-zip payload from {} ({} bytes)", operationName, uri, size); - throw new IllegalStateException("Server returned non-zip content for " + operationName + " download"); - } - - Files.move(tempPath, destinationPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - LOGGER.info("Download complete: {} ({} bytes)", destinationPath.getFileName(), Files.size(destinationPath)); - return destinationPath; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOGGER.error("{} download interrupted for {}", operationName, uri, e); - throw new IllegalStateException(operationName + " download interrupted", e); - } catch (IOException e) { - LOGGER.error("Failed to persist {} download to {}", operationName, destinationPath, e); - throw new IllegalStateException("Failed to persist " + operationName + " download", e); - } - } - - private boolean looksLikeZip(Path path) throws IOException { - byte[] header = new byte[4]; - try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { - int read = in.read(header); - if (read < 4) { - return false; - } - } - - return header[0] == 'P' - && header[1] == 'K' - && ((header[2] == 3 && header[3] == 4) - || (header[2] == 5 && header[3] == 6) - || (header[2] == 7 && header[3] == 8)); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java deleted file mode 100644 index 5de7b05..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java +++ /dev/null @@ -1,293 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.http.HttpClient; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.springframework.http.HttpStatusCode; -import org.springframework.http.client.JdkClientHttpRequestFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClient; -import org.springframework.web.client.RestClientException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ServerDiscoveryService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); - - private static final int MIN_NON_STANDARD_PORT = 1024; - private static final int MAX_PORT = 65535; - private static final int PORT_SCAN_THREADS = 128; - private static final int DISCOVERY_THREADS = 64; - - private final Configuration configuration; - private final RestClient restClient; - - public ServerDiscoveryService(Configuration configuration) { - this.configuration = configuration; - HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.NORMAL) - .connectTimeout(Duration.ofMillis(2500)) - .build(); - JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); - requestFactory.setReadTimeout(Duration.ofMillis(3000)); - this.restClient = RestClient.builder().requestFactory(requestFactory).build(); - } - - public List discover() { - List prefixes = localPrefixes(); - Set discovered = new java.util.LinkedHashSet<>(); - - LOGGER.info("Starting network discovery: localPrefixes={}", prefixes); - - String preferredServerIp = configuration.getPreferredServerIp(); - if (preferredServerIp != null && !preferredServerIp.isBlank()) { - LOGGER.info("Probing preferred server IP: {}", preferredServerIp); - resolveServerByIp(preferredServerIp).ifPresent(url -> { - LOGGER.info("Preferred IP resolved: {}", url); - discovered.add(url); - }); - } - - if (prefixes.isEmpty()) { - LOGGER.warn("No local network prefixes detected, skipping subnet scan"); - return discovered.stream().toList(); - } - - List portsToProbe = discoveryPorts(); - LOGGER.info("Scanning {} subnet prefix(es) with {} port(s) each, ports={}", prefixes.size(), portsToProbe.size(), portsToProbe); - Set candidates = new java.util.LinkedHashSet<>(); - for (String prefix : prefixes) { - for (int host = 1; host <= 254; host++) { - String ip = prefix + "." + host; - for (Integer port : portsToProbe) { - candidates.add("http://" + ip + ":" + port); - } - } - } - - ExecutorService executor = Executors.newFixedThreadPool(DISCOVERY_THREADS); - LOGGER.info("Probing {} candidate endpoints with {} threads", candidates.size(), DISCOVERY_THREADS); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (String candidate : candidates) { - completionService.submit(() -> isHealthy(candidate) ? candidate : null); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - try { - String healthy = completionService.take().get(); - if (healthy != null) { - LOGGER.info("Discovered server: {}", healthy); - discovered.add(healthy); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - break; - } catch (ExecutionException ignored) { - } - } - } finally { - executor.shutdownNow(); - } - - LOGGER.info("Network discovery complete, found {} server(s): {}", discovered.size(), discovered); - return discovered.stream().toList(); - } - - private List discoveryPorts() { - Set ports = new java.util.LinkedHashSet<>(); - ports.add(configuration.getServerPort()); - ports.add(38471); - ports.add(8080); - ports.add(3000); - ports.add(5000); - ports.add(8081); - ports.add(80); - ports.add(443); - return new ArrayList<>(ports); - } - - public Optional resolveServerByIp(String input) { - return resolveServerByIp(input, null); - } - - public Optional resolveServerByIp(String input, Integer preferredPort) { - String host = normalizeHost(input); - if (host == null) { - LOGGER.warn("resolveServerByIp: invalid input '{}'", input); - return Optional.empty(); - } - - LOGGER.info("Resolving server at host={}, preferredPort={}", host, preferredPort); - - if (preferredPort != null) { - String preferredCandidate = toUrl(host, preferredPort); - LOGGER.debug("Probing preferred port: {}", preferredCandidate); - if (isHealthy(preferredCandidate)) { - LOGGER.info("Server found at preferred port: {}", preferredCandidate); - return Optional.of(preferredCandidate); - } - LOGGER.debug("Preferred port {} not responding", preferredPort); - } - - int defaultPort = configuration.getServerPort(); - String defaultCandidate = toUrl(host, defaultPort); - LOGGER.debug("Probing default port: {}", defaultCandidate); - if (isHealthy(defaultCandidate)) { - LOGGER.info("Server found at default port: {}", defaultCandidate); - return Optional.of(defaultCandidate); - } - - LOGGER.debug("Default port {} not responding, trying common ports", defaultPort); - for (Integer quickPort : discoveryPorts()) { - if (quickPort == defaultPort) { - continue; - } - if (preferredPort != null && quickPort.equals(preferredPort)) { - continue; - } - String quickCandidate = toUrl(host, quickPort); - LOGGER.debug("Probing common port: {}", quickCandidate); - if (isHealthy(quickCandidate)) { - LOGGER.info("Server found at common port: {}", quickCandidate); - return Optional.of(quickCandidate); - } - } - - LOGGER.info("Common ports exhausted for {}, starting full port scan ({}-{})", host, MIN_NON_STANDARD_PORT, MAX_PORT); - ExecutorService executor = Executors.newFixedThreadPool(PORT_SCAN_THREADS); - AtomicBoolean stop = new AtomicBoolean(false); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (int port = MIN_NON_STANDARD_PORT; port <= MAX_PORT; port++) { - if (port == defaultPort) { - continue; - } - if (preferredPort != null && port == preferredPort) { - continue; - } - - final int candidatePort = port; - completionService.submit(() -> { - if (stop.get()) { - return null; - } - String candidate = toUrl(host, candidatePort); - if (isHealthy(candidate)) { - stop.set(true); - return candidate; - } - return null; - }); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - String candidate = completionService.take().get(); - if (candidate != null) { - LOGGER.info("Server found via full port scan: {}", candidate); - return Optional.of(candidate); - } - } - LOGGER.warn("Full port scan exhausted for {}, no server found", host); - return Optional.empty(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - LOGGER.warn("Port scan interrupted for {}", host); - return Optional.empty(); - } catch (ExecutionException ex) { - LOGGER.warn("Port scan execution error for {}: {}", host, ex.getMessage()); - return Optional.empty(); - } finally { - executor.shutdownNow(); - } - } - - private List localPrefixes() { - List prefixes = new ArrayList<>(); - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces.hasMoreElements()) { - NetworkInterface networkInterface = interfaces.nextElement(); - if (!networkInterface.isUp() || networkInterface.isLoopback()) { - continue; - } - Enumeration addresses = networkInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (address instanceof Inet4Address ipv4 && !ipv4.isLoopbackAddress()) { - byte[] bytes = ipv4.getAddress(); - prefixes.add((bytes[0] & 0xFF) + "." + (bytes[1] & 0xFF) + "." + (bytes[2] & 0xFF)); - } - } - } - } catch (SocketException ignored) { - } - return prefixes.stream().distinct().toList(); - } - - private boolean isHealthy(String candidate) { - try { - HttpStatusCode status = restClient.get() - .uri(candidate + "/api/v1/health") - .retrieve() - .toBodilessEntity() - .getStatusCode(); - boolean ok = status.is2xxSuccessful(); - if (ok) { - LOGGER.debug("Health check OK: {}", candidate); - } - return ok; - } catch (RestClientException ex) { - LOGGER.debug("Health check failed for {}: {}", candidate, ex.getMessage()); - return false; - } - } - - private String normalizeHost(String input) { - if (input == null) { - return null; - } - String trimmed = input.trim(); - if (trimmed.isBlank()) { - return null; - } - - try { - URI uri = trimmed.contains("://") ? URI.create(trimmed) : URI.create("http://" + trimmed); - if (uri.getHost() != null && !uri.getHost().isBlank()) { - return uri.getHost(); - } - } catch (IllegalArgumentException ignored) { - } - return trimmed; - } - - private String toUrl(String host, int port) { - return "http://" + host + ":" + port; - } -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index fdda830..3a82616 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,10 +1,16 @@ server: port: ${CLIENT_PORT:8081} +spring: + web: + resources: + cache: + period: 0 + mediagarrd: client: - state-file: ${CLIENT_STATE_FILE:./data/client/state.json} - download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:./data/client/downloads} + state-file: ${CLIENT_STATE_FILE:/var/lib/mediagarrd/client/state.json} + download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:/var/lib/mediagarrd/downloads} pickup-interval: ${CLIENT_PICKUP_INTERVAL:PT12H} - server-port: ${MEDIAGARRD_SERVER_PORT:8080} + server-port: ${MEDIAGARRD_SERVER_PORT:38471} preferred-server-ip: ${MEDIAGARRD_SERVER_IP:} diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css new file mode 100644 index 0000000..b749ca2 --- /dev/null +++ b/src/main/resources/static/css/mediagarrd.css @@ -0,0 +1,305 @@ +:root { + --bg: #000; + --surface: #0a0a0a; + --surface-raised: #111; + --ink: #f5f5f5; + --muted: #737373; + --subtle: #404040; + --border: #1f1f1f; + --border-mid: #2e2e2e; + --accent: #f5f5f5; + --accent-dim: #d4d4d4; + --ok: #22c55e; + --warn: #ef4444; + --mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; +} + +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +body { + font-family: "Space Grotesk", "Inter", "Avenir Next", ui-sans-serif, system-ui, sans-serif; + background: var(--bg); + color: var(--ink); + min-height: 100vh; + font-size: 14px; + line-height: 1.5; +} + +[hidden] { display: none !important; } + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + padding: 0.85rem 1.5rem; + border-bottom: 1px solid var(--border); + background: var(--surface); + position: sticky; + top: 0; + z-index: 10; +} + +.brand { display: flex; flex-direction: column; } +.brand-title { font-size: 1rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; } +.brand-sub { font-size: 0.72rem; color: var(--muted); letter-spacing: 0.05em; } + +.view-toggle { display: flex; border: 1px solid var(--border-mid); } +.view-toggle button { background: transparent; color: var(--muted); border: none; padding: 0.4rem 0.85rem; } +.view-toggle button:hover { background: var(--surface-raised); color: var(--ink); } +.view-toggle button[aria-pressed="true"] { background: var(--accent); color: #000; } + +.conn-badge { + display: flex; + align-items: center; + gap: 0.45rem; + padding: 0.32rem 0.75rem; + border: 1px solid var(--border-mid); + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted); + background: var(--surface-raised); + white-space: nowrap; +} +.conn-badge .dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--subtle); + flex-shrink: 0; + transition: background 300ms; +} +.conn-badge.ok { color: #a3e8bc; border-color: #1e3b2a; } +.conn-badge.ok .dot { background: var(--ok); box-shadow: 0 0 6px var(--ok); } +.conn-badge.down { color: #fca5a5; border-color: #3b1111; } +.conn-badge.down .dot { background: var(--warn); box-shadow: 0 0 6px var(--warn); } +.conn-badge.checking { color: var(--accent-dim); } +.conn-badge.checking .dot { background: #a3a3a3; } + +.page { max-width: 1200px; margin: 0 auto; padding: 1.5rem; animation: fadein 350ms ease; } +.workspace { + display: grid; + grid-template-columns: 360px 1fr; + gap: 1rem; + align-items: start; +} +@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } + +.panel { background: var(--surface); border: 1px solid var(--border); } +.panel.wide { grid-column: 1 / -1; } +.stack { display: flex; flex-direction: column; gap: 1rem; } +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--border); +} +.panel-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent-dim); } +.panel-body { padding: 1rem; } +.panel-body + .panel-body { border-top: 1px solid var(--border); } +.section-label { + font-size: 0.68rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + margin-bottom: 0.6rem; +} + +.field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } +.field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } +.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } +.input-row-2 { display: grid; grid-template-columns: 1fr 110px; gap: 0.5rem; } +.button-row { display: flex; gap: 0.5rem; flex-wrap: wrap; } +.button-row > button { flex: 1; } + +input, select { + width: 100%; + background: var(--bg); + color: var(--ink); + border: 1px solid var(--border-mid); + padding: 0.5rem 0.65rem; + font: inherit; + font-size: 0.85rem; + outline: none; + transition: border-color 150ms; +} +input:focus, select:focus { border-color: var(--subtle); } +input::placeholder { color: var(--muted); } + +button { + background: var(--accent); + color: #000; + border: 1px solid var(--accent); + padding: 0.5rem 0.85rem; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; + white-space: nowrap; + transition: background 120ms, color 120ms, border-color 120ms, transform 70ms, box-shadow 120ms; +} +button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } +button:active, button.clicked { transform: translateY(1px) scale(0.98); box-shadow: inset 0 0 0 2px #000; } +button:disabled { cursor: not-allowed; opacity: 0.62; transform: none; } +button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } +button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } +button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } +button.danger:hover { background: #1c0606; } +button.full { width: 100%; } +button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } + +.action-btn { position: relative; overflow: hidden; } +.action-btn .btn-label { position: relative; z-index: 1; } +.btn-progress { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 2px; + display: none; + background: rgba(255, 255, 255, 0.12); + overflow: hidden; +} +.action-btn.busy .btn-progress { display: block; } +.btn-progress.indeterminate::after { + content: ''; + display: block; + width: 34%; + height: 100%; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.85), transparent); + animation: sweep 1.1s linear infinite; +} +.btn-progress-fill { + display: block; + width: 0; + height: 100%; + background: linear-gradient(90deg, #9ca3af, #f5f5f5); + transition: width 120ms linear; +} + +.stat-row { + display: flex; + align-items: baseline; + justify-content: space-between; + padding: 0.35rem 0; + border-bottom: 1px solid var(--border); + font-size: 0.83rem; +} +.stat-row:last-child { border-bottom: none; } +.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; } + +.tag { + display: inline-block; + padding: 0.12rem 0.45rem; + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.07em; + text-transform: uppercase; + border: 1px solid var(--border-mid); + color: var(--muted); +} +.tag.running { color: #a3e8bc; border-color: #1e3b2a; } + +.scan-bar { display: none; height: 2px; background: var(--border); overflow: hidden; margin-top: 0.6rem; } +.scan-bar.active { display: block; } +.scan-bar > span { + display: block; + width: 30%; + height: 100%; + background: linear-gradient(90deg, transparent, var(--accent-dim), transparent); + animation: sweep 1.1s linear infinite; +} + +.server-url { + font-family: var(--mono); + font-size: 0.78rem; + color: var(--accent-dim); + word-break: break-all; + padding: 0.4rem 0.6rem; + background: var(--surface-raised); + border: 1px solid var(--border); + margin-bottom: 0.75rem; +} + +table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } +thead th { + padding: 0.5rem 0.75rem; + text-align: left; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + border-bottom: 1px solid var(--border-mid); +} +thead th.sortable { cursor: pointer; user-select: none; transition: color 120ms; white-space: nowrap; } +thead th.sortable:hover, thead th.sortable.active { color: var(--accent-dim); } +.sort-indicator { margin-left: 0.25rem; font-size: 0.65rem; color: var(--subtle); vertical-align: middle; } +thead th.sortable.active .sort-indicator { color: var(--accent-dim); } +tbody tr { border-bottom: 1px solid var(--border); transition: background 100ms; } +tbody tr:last-child { border-bottom: none; } +tbody tr:hover { background: var(--surface-raised); } +tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } +.td-mono { font-family: var(--mono); font-size: 0.78rem; color: var(--accent-dim); white-space: pre-line; word-break: break-all; } +.td-muted { color: var(--muted); } +.td-id { font-size: 0.7rem; } +.actions-cell { text-align: right; white-space: nowrap; } +.actions-cell button + button { margin-left: 0.4rem; } +.empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } + +.icon-btn { + min-width: 34px; + height: 28px; + padding: 0; + font-size: 0.95rem; + line-height: 1; + font-weight: 800; + letter-spacing: 0; + text-transform: none; +} +.row-progress-circle { + width: 16px; + height: 16px; + border-radius: 50%; + display: inline-block; + position: relative; + background: conic-gradient(var(--accent-dim) var(--p, 0%), var(--border-mid) 0); +} +.row-progress-circle::after { + content: ''; + position: absolute; + inset: 3px; + border-radius: 50%; + background: var(--surface); +} + +.banner { + display: none; + margin-bottom: 1rem; + padding: 0.65rem 1rem; + font-size: 0.82rem; + background: #1c0606; + border: 1px solid #3b1111; + color: #fca5a5; +} +.banner.visible { display: block; } +.banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } + +@keyframes sweep { + from { transform: translateX(-150%); } + to { transform: translateX(420%); } +} + +@keyframes fadein { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index f15c498..73c4516 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -4,1198 +4,207 @@ MediaGarrd Client - + + - -

MediaGarrd Client Dashboard
+
- Connecting... + Connecting...
-
+
+ - -
-
- Server Connection -
+
+
+
Server Connection
- -
- -
-
- - +
+ +
+
+ + +
-
- -
+ + - -
- -
- +
+ +
+ +
+
- -
- - -
- - - -

Last scan: not run yet.

-
-
- - -
-
- Server Status -
- -
-
No server connected.
-
+ +
+
Server Status
+ +
+

No server connected.

+
-
- -
- -
- - +
+ +
+ + +
-
- -
- -
- - -
-
- - +
+ +
+ + +
+ +
+ + +
+
+ Backup Archives +
-
- - - -
- - -
-
- Backup Archives - -
- - +
+ + + + + + + + + + +
File Size Created ID Get
+

No backups loaded. Connect to a server to view archives.

+ + +
+
+ +
+ + + +
+ diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js new file mode 100644 index 0000000..7e636d3 --- /dev/null +++ b/src/main/resources/static/js/api.js @@ -0,0 +1,34 @@ +async function request(method, url, body) { + const response = await fetch(url, { + method, + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => ({})); + throw new Error(data.error || data.message || `${method} ${url} failed (${response.status})`); + } + const text = await response.text(); + return text ? JSON.parse(text) : null; +} + +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'), + selectServer: (selection) => request('PUT', '/api/client/server', selection), + listBackups: () => request('GET', '/api/client/backups'), + runBackup: () => request('POST', '/api/client/backups/run'), + pickupLatest: () => request('POST', '/api/client/pickup'), + pickupById: (id) => request('POST', `/api/client/pickup/${encode(id)}`), + pickupProgress: (taskId) => request('GET', `/api/client/pickup/progress/${encode(taskId)}`), + updatePickupInterval: (interval) => request('PUT', '/api/client/pickup-interval', { interval }), + serverConfig: () => request('GET', '/api/client/server-config'), + updateServerConfig: (config) => request('PUT', '/api/client/server-config', config), + listServices: () => request('GET', '/api/client/services'), + addService: (service) => request('POST', '/api/client/services', service), + updateService: (name, service) => request('PUT', `/api/client/services/${encode(name)}`, service), + removeService: (name) => request('DELETE', `/api/client/services/${encode(name)}`), +}; diff --git a/src/main/resources/static/js/backups.js b/src/main/resources/static/js/backups.js new file mode 100644 index 0000000..4d9aba4 --- /dev/null +++ b/src/main/resources/static/js/backups.js @@ -0,0 +1,206 @@ +import { api } from './api.js'; +import { bytes, percent, relativeTime } from './format.js'; + +const POLL_INTERVAL_MS = 350; + +export function initBackups({ root, actions }, notify, { refreshHealth }) { + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const headers = root.querySelectorAll('th[data-sort-key]'); + const template = root.querySelector('#backupTemplate'); + const runButton = actions.querySelector('[data-run]'); + const pickupButton = actions.querySelector('[data-pickup]'); + const sort = { key: 'fileName', dir: 'asc' }; + const rowTasks = new Map(); + const rowButtons = new Map(); + let backups = []; + let serverRunning = false; + let runInFlight = false; + let latestTask = null; + let pollTimer = null; + + function renderActions() { + const backupBusy = serverRunning || runInFlight; + runButton.disabled = backupBusy; + runButton.classList.toggle('busy', backupBusy); + runButton.querySelector('.btn-label').textContent = backupBusy ? 'Backup In Progress' : 'Run Backup Now'; + + pickupButton.disabled = Boolean(latestTask); + pickupButton.classList.toggle('busy', Boolean(latestTask)); + pickupButton.querySelector('.btn-label').textContent = latestTask ? 'Downloading...' : 'Download Latest'; + pickupButton.querySelector('.btn-progress-fill').style.width = + `${latestTask ? percent(latestTask.bytesWritten, latestTask.totalBytes) : 0}%`; + } + + function renderRowButton(id) { + const button = rowButtons.get(id); + if (!button) return; + const task = rowTasks.get(id); + button.disabled = Boolean(task); + if (!task) { + button.textContent = '↓'; + return; + } + const progress = document.createElement('span'); + progress.className = 'row-progress-circle'; + progress.style.setProperty('--p', `${percent(task.bytesWritten, task.totalBytes)}%`); + button.replaceChildren(progress); + } + + function compare(a, b) { + const dir = sort.dir === 'asc' ? 1 : -1; + if (sort.key === 'sizeBytes') return ((a.sizeBytes ?? 0) - (b.sizeBytes ?? 0)) * dir; + if (sort.key === 'createdAt') return (new Date(a.createdAt) - new Date(b.createdAt)) * dir; + return String(a[sort.key] ?? '').localeCompare(String(b[sort.key] ?? ''), undefined, { sensitivity: 'base' }) * dir; + } + + function renderRow(backup) { + const row = template.content.firstElementChild.cloneNode(true); + row.querySelector('[data-file]').textContent = backup.fileName; + row.querySelector('[data-size]').textContent = bytes(backup.sizeBytes); + row.querySelector('[data-created]').textContent = relativeTime(backup.createdAt); + const id = row.querySelector('[data-id]'); + id.textContent = backup.id.length > 22 ? `${backup.id.slice(0, 22)}…` : backup.id; + id.title = backup.id; + const button = row.querySelector('button'); + button.addEventListener('click', () => pickupById(backup.id)); + rowButtons.set(backup.id, button); + renderRowButton(backup.id); + return row; + } + + function renderTable(emptyMessage = 'No backup archives found on server.') { + headers.forEach((header) => { + const active = header.dataset.sortKey === sort.key; + header.classList.toggle('active', active); + header.querySelector('.sort-indicator').textContent = active ? (sort.dir === 'asc' ? '▲' : '▼') : '↕'; + }); + rowButtons.clear(); + rows.replaceChildren(...[...backups].sort(compare).map(renderRow)); + empty.textContent = emptyMessage; + empty.hidden = backups.length > 0; + } + + async function refresh() { + try { + backups = await api.listBackups() || []; + renderTable(); + } catch (error) { + backups = []; + renderTable(`${error.message}. Connect to a server to view archives.`); + } + } + + function finish(id) { + if (id === null) { + latestTask = null; + renderActions(); + refresh(); + } else { + rowTasks.delete(id); + renderRowButton(id); + } + } + + async function poll() { + const tasks = [...rowTasks].map(([id, task]) => ({ id, task })); + if (latestTask?.taskId) tasks.push({ id: null, task: latestTask }); + if (!tasks.length) { + pollTimer = null; + return; + } + await Promise.all(tasks.map(async ({ id, task }) => { + try { + const progress = await api.pickupProgress(task.taskId); + task.bytesWritten = progress.bytesWritten || 0; + task.totalBytes = progress.totalBytes || task.totalBytes; + if (progress.status === 'FAILED') notify.error(progress.error || 'Download failed'); + if (progress.status === 'COMPLETED' || progress.status === 'FAILED') finish(id); + } catch (error) { + notify.error(error); + finish(id); + } + })); + rowTasks.forEach((_, id) => renderRowButton(id)); + renderActions(); + pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + } + + function startPolling() { + if (!pollTimer) pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + } + + const toTask = (started) => ({ taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }); + + async function pickupById(id) { + if (rowTasks.has(id)) return; + notify.clear(); + try { + rowTasks.set(id, toTask(await api.pickupById(id))); + renderRowButton(id); + startPolling(); + } catch (error) { + notify.error(error); + } + } + + pickupButton.addEventListener('click', async () => { + if (latestTask) return; + notify.clear(); + latestTask = { taskId: null, bytesWritten: 0, totalBytes: 0 }; + renderActions(); + try { + latestTask = toTask(await api.pickupLatest()); + startPolling(); + } catch (error) { + latestTask = null; + notify.error(error); + } + renderActions(); + }); + + runButton.addEventListener('click', async () => { + if (serverRunning || runInFlight) return; + notify.clear(); + runInFlight = true; + renderActions(); + try { + await api.runBackup(); + await refresh(); + } catch (error) { + notify.error(error); + } finally { + runInFlight = false; + await refreshHealth(); + } + }); + + headers.forEach((header) => header.addEventListener('click', () => { + const key = header.dataset.sortKey; + if (sort.key === key) { + sort.dir = sort.dir === 'asc' ? 'desc' : 'asc'; + } else { + sort.key = key; + sort.dir = key === 'createdAt' ? 'desc' : 'asc'; + } + renderTable(); + })); + + root.querySelector('[data-refresh]').addEventListener('click', () => { + notify.clear(); + refresh(); + }); + + renderTable('No backups loaded. Connect to a server to view archives.'); + renderActions(); + + return { + refresh, + 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 new file mode 100644 index 0000000..a081ce6 --- /dev/null +++ b/src/main/resources/static/js/connection.js @@ -0,0 +1,115 @@ +import { api } from './api.js'; +import { formatInterval } from './format.js'; + +export function initConnection({ root, statusPanel, badge }, notify, { onServerChanged, onHealth, onStatus }) { + const ipForm = root.querySelector('[data-ip-form]'); + const known = root.querySelector('[data-known]'); + const controls = root.querySelectorAll('button, input, select'); + const scanBar = root.querySelector('[data-scan-bar]'); + 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]'); + let busy = false; + let connected = null; + let healthRequest = null; + + 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 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(); + } + + async function connect(label, action) { + if (busy) return null; + notify.clear(); + busy = true; + setBadge('checking', label); + scanBar.classList.add('active'); + controls.forEach((control) => { control.disabled = true; }); + let result = null; + try { + result = await action(); + } catch (error) { + notify.error(error); + } + busy = false; + scanBar.classList.remove('active'); + controls.forEach((control) => { control.disabled = false; }); + connected = null; + await refreshStatus().catch(notify.error); + if (result) onServerChanged(); + return result; + } + + ipForm.addEventListener('submit', (event) => { + event.preventDefault(); + const { ip, port } = ipForm.elements; + connect('Probing…', () => api.selectServer({ + serverIp: ip.value.trim(), + serverPort: port.value ? Number(port.value) : null, + })); + }); + + root.querySelector('[data-connect-known]').addEventListener('click', () => { + if (!known.value) { + notify.error('No server selected.'); + return; + } + connect('Connecting…', () => api.selectServer({ serverUrl: known.value })); + }); + + root.querySelector('[data-discover]').addEventListener('click', async () => { + if (busy) return; + scanNote.textContent = 'Scan in progress…'; + const found = await connect('Scanning…', api.discover); + const count = found?.length ?? 0; + scanNote.textContent = found ? `Last scan: found ${count} server${count === 1 ? '' : 's'}.` : 'Last scan: failed.'; + }); + + return { refreshStatus, refreshHealth }; +} diff --git a/src/main/resources/static/js/format.js b/src/main/resources/static/js/format.js new file mode 100644 index 0000000..68a82b6 --- /dev/null +++ b/src/main/resources/static/js/format.js @@ -0,0 +1,44 @@ +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i; + +export function seconds(duration) { + if (typeof duration === 'number') return duration; + const [, hours = 0, minutes = 0, secs = 0] = ISO_DURATION.exec(duration ?? '') || []; + return Number(hours) * 3600 + Number(minutes) * 60 + Number(secs); +} + +export const toDuration = (minutes) => `PT${Math.round(minutes)}M`; + +export function formatInterval(duration) { + const total = seconds(duration); + if (!total) return '—'; + if (total < 60) return `${total}s`; + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + return [hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' '); +} + +export function bytes(size) { + if (!size) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let unit = 0; + let value = size; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return `${value.toFixed(unit > 0 ? 1 : 0)} ${units[unit]}`; +} + +export function relativeTime(iso) { + const elapsed = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000)); + if (elapsed < 60) return `${elapsed}s ago`; + const minutes = Math.floor(elapsed / 60); + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + return `${Math.floor(hours / 24)}d ago`; +} + +export function percent(written, total) { + return total > 0 ? Math.max(0, Math.min(100, Math.floor((written / total) * 100))) : 0; +} diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js new file mode 100644 index 0000000..aaaa268 --- /dev/null +++ b/src/main/resources/static/js/main.js @@ -0,0 +1,50 @@ +import { initBackups } from './backups.js'; +import { initConnection } from './connection.js'; +import { createNotifier } from './notify.js'; +import { initPickupInterval } from './pickup-interval.js'; +import { initServerConfig } from './server-config.js'; +import { initViews } from './views.js'; + +const HEALTH_INTERVAL_MS = 7000; + +const notify = createNotifier(document.getElementById('banner')); +const pickupInterval = initPickupInterval(document.getElementById('pickupIntervalForm'), notify); +const serverConfig = initServerConfig(document.querySelector('[data-view="config"]'), notify); +const backups = initBackups({ + root: document.getElementById('backups'), + actions: document.getElementById('actions'), +}, notify, { refreshHealth: () => connection.refreshHealth() }); + +const connection = initConnection({ + root: document.getElementById('connection'), + statusPanel: document.getElementById('serverStatus'), + badge: document.getElementById('connBadge'), +}, notify, { + onServerChanged: () => { + backups.refresh(); + serverConfig.serverChanged(); + }, + onHealth: (health) => backups.setServerRunning(Boolean(health.serverStatus?.running)), + onStatus: (status) => pickupInterval.show(status.pickupInterval), +}); + +document.addEventListener('click', (event) => { + const button = event.target.closest('button'); + if (!button) return; + button.classList.add('clicked'); + setTimeout(() => button.classList.remove('clicked'), 140); +}); + +initViews((view) => { + notify.clear(); + if (view === 'config') serverConfig.load(); + else connection.refreshHealth(); +}); + +connection.refreshStatus().catch(notify.error).then(backups.refresh); +setInterval(() => { + if (!document.hidden) connection.refreshHealth(); +}, HEALTH_INTERVAL_MS); +document.addEventListener('visibilitychange', () => { + if (!document.hidden) connection.refreshHealth(); +}); diff --git a/src/main/resources/static/js/notify.js b/src/main/resources/static/js/notify.js new file mode 100644 index 0000000..ddbe743 --- /dev/null +++ b/src/main/resources/static/js/notify.js @@ -0,0 +1,12 @@ +export function createNotifier(banner) { + function show(message, kind) { + banner.textContent = message; + banner.className = `banner visible ${kind}`; + } + + return { + ok: (message) => show(message, 'ok'), + error: (error) => show(error.message || String(error), 'error'), + clear: () => { banner.className = 'banner'; }, + }; +} diff --git a/src/main/resources/static/js/pickup-interval.js b/src/main/resources/static/js/pickup-interval.js new file mode 100644 index 0000000..c071e5b --- /dev/null +++ b/src/main/resources/static/js/pickup-interval.js @@ -0,0 +1,25 @@ +import { api } from './api.js'; +import { seconds, toDuration } from './format.js'; + +export function initPickupInterval(form, notify) { + const minutes = form.elements.minutes; + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + try { + const status = await api.updatePickupInterval(toDuration(Number(minutes.value))); + show(status.pickupInterval); + notify.ok('Pickup interval saved'); + } catch (error) { + notify.error(error); + } + }); + + function show(interval) { + const value = Math.round(seconds(interval) / 60); + if (value) minutes.value = value; + } + + return { show }; +} diff --git a/src/main/resources/static/js/server-config.js b/src/main/resources/static/js/server-config.js new file mode 100644 index 0000000..9a46998 --- /dev/null +++ b/src/main/resources/static/js/server-config.js @@ -0,0 +1,33 @@ +import { api } from './api.js'; +import { initServices } from './services.js'; +import { initSettings } from './settings.js'; + +export function initServerConfig(root, notify) { + const content = root.querySelector('[data-config-content]'); + const unavailable = root.querySelector('[data-unavailable]'); + const settings = initSettings(root.querySelector('#settingsForm'), notify); + const services = initServices(root.querySelector('#services'), notify); + + async function load() { + try { + const [config, list] = await Promise.all([api.serverConfig(), api.listServices()]); + settings.show(config); + services.show(list); + content.hidden = false; + unavailable.hidden = true; + } catch (error) { + content.hidden = true; + unavailable.hidden = false; + unavailable.querySelector('[data-reason]').textContent = + `${error.message}. Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; + } + } + + return { + load, + serverChanged() { + services.resetForm(); + if (!root.hidden) load(); + }, + }; +} diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js new file mode 100644 index 0000000..0c0ab09 --- /dev/null +++ b/src/main/resources/static/js/services.js @@ -0,0 +1,96 @@ +import { api } from './api.js'; + +export function initServices(root, notify) { + const form = root.querySelector('form'); + const title = root.querySelector('[data-form-title]'); + const paths = root.querySelector('[data-paths]'); + const cancel = root.querySelector('[data-cancel]'); + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const pathTemplate = root.querySelector('#pathTemplate'); + const rowTemplate = root.querySelector('#serviceTemplate'); + let editing = null; + + function addPathInput(value = '') { + const row = pathTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('input').value = value; + row.querySelector('button').addEventListener('click', () => { + row.remove(); + if (!paths.children.length) addPathInput(); + }); + paths.append(row); + } + + function resetForm() { + editing = null; + form.reset(); + paths.replaceChildren(); + addPathInput(); + title.textContent = 'Add Service'; + cancel.hidden = true; + } + + function editService(service) { + editing = service.name; + form.elements.name.value = service.name; + paths.replaceChildren(); + service.paths.forEach((path) => addPathInput(path)); + title.textContent = `Edit ${service.name}`; + cancel.hidden = false; + form.elements.name.focus(); + } + + async function removeService(service) { + if (!confirm(`Remove ${service.name}? Existing backups are kept.`)) return; + notify.clear(); + try { + await api.removeService(service.name); + if (editing === service.name) resetForm(); + notify.ok(`Removed ${service.name}`); + await refresh(); + } catch (error) { + notify.error(error); + } + } + + function renderRow(service) { + const row = rowTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('[data-name]').textContent = service.name; + row.querySelector('[data-paths]').textContent = service.paths.join('\n'); + row.querySelector('[data-edit]').addEventListener('click', () => editService(service)); + row.querySelector('[data-remove]').addEventListener('click', () => removeService(service)); + return row; + } + + function show(services) { + rows.replaceChildren(...services.map(renderRow)); + empty.hidden = services.length > 0; + } + + async function refresh() { + show(await api.listServices()); + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const service = { + name: form.elements.name.value, + paths: [...paths.querySelectorAll('input')].map((input) => input.value), + }; + try { + const saved = editing ? await api.updateService(editing, service) : await api.addService(service); + notify.ok(`Saved ${saved.name}`); + resetForm(); + await refresh(); + } catch (error) { + notify.error(error); + } + }); + + root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); + cancel.addEventListener('click', resetForm); + + resetForm(); + return { show, resetForm }; +} diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js new file mode 100644 index 0000000..cd2cf08 --- /dev/null +++ b/src/main/resources/static/js/settings.js @@ -0,0 +1,29 @@ +import { api } from './api.js'; +import { seconds, toDuration } from './format.js'; + +export function initSettings(form, notify) { + const { backupLocation, intervalHours, retentionCount } = form.elements; + + function show(config) { + backupLocation.value = config.backupLocation; + intervalHours.value = seconds(config.backupInterval) / 3600; + retentionCount.value = config.retentionCount; + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + try { + show(await api.updateServerConfig({ + backupLocation: backupLocation.value, + retentionCount: Number(retentionCount.value), + backupInterval: toDuration(Number(intervalHours.value) * 60), + })); + notify.ok('Backup settings saved'); + } catch (error) { + notify.error(error); + } + }); + + return { show }; +} diff --git a/src/main/resources/static/js/views.js b/src/main/resources/static/js/views.js new file mode 100644 index 0000000..18bd5db --- /dev/null +++ b/src/main/resources/static/js/views.js @@ -0,0 +1,17 @@ +export function initViews(onShow) { + const views = document.querySelectorAll('[data-view]'); + const links = document.querySelectorAll('[data-view-link]'); + + function show() { + const current = location.hash === '#config' ? 'config' : 'dashboard'; + views.forEach((view) => { view.hidden = view.dataset.view !== current; }); + links.forEach((link) => link.setAttribute('aria-pressed', String(link.dataset.viewLink === current))); + onShow(current); + } + + links.forEach((link) => link.addEventListener('click', () => { + location.hash = link.dataset.viewLink === 'config' ? 'config' : ''; + })); + window.addEventListener('hashchange', show); + show(); +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java new file mode 100644 index 0000000..2a6aa76 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient; + +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.status; + +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +class MediaGarrdTest { + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @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", () -> ""); + } + + @Test + void servesTheWebPageAndItsAssets() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/css/mediagarrd.css")) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", "no-store")); + mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); + } + + @Test + void reportsStatusWithoutAServer() throws Exception { + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java new file mode 100644 index 0000000..b59d047 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -0,0 +1,170 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +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; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +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.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; + +@WebMvcTest(controllers = ClientController.class) +class ClientControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + ClientStateService stateService; + + @MockBean + ServerDiscoveryService discoveryService; + + @MockBean + ServerApiService serverApiService; + + @MockBean + BackupPickupService backupPickupService; + + @Test + void statusEndpointReturnsState() throws Exception { + when(stateService.getActiveServer()).thenReturn("http://server:8080"); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); + + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.activeServer").value("http://server:8080")); + } + + @Test + void discoverEndpointReturnsOnlyTheServersFoundByTheScan() throws Exception { + when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080", "http://active:38471")); + + mockMvc.perform(post("/api/client/discover")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0]").value("http://server:8080")); + + verify(stateService).updateKnownServers(List.of("http://server:8080")); + } + + @Test + void listBackupsReturnsServerData() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value("id")); + } + + @Test + void setServerEndpointAcceptsUpdate() throws Exception { + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); + when(stateService.getActiveServer()).thenReturn("http://server:8080"); + + mockMvc.perform(put("/api/client/server") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"serverUrl\":\"http://server:8080\"}")) + .andExpect(status().isOk()); + } + + @Test + void pickupEndpointStartsTask() throws Exception { + when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "id", "file.zip", 10L)); + + mockMvc.perform(post("/api/client/pickup")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("task-1")) + .andExpect(jsonPath("$.backupId").value("id")); + } + + @Test + void statusConnectsThePreferredServerFirst() throws Exception { + mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); + + verify(discoveryService).connectPreferredServer(); + } + + @Test + void normalizesSelectedServerUrls() throws Exception { + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\" http://server:8080/ \"}")) + .andExpect(status().isOk()); + + verify(stateService).setActiveServer("http://server:8080"); + } + + @Test + void rejectsInvalidServerSelections() throws Exception { + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"ftp://server\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverUrl must be an http:// or https:// URL: ftp://server")); + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\",\"serverPort\":70000}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverPort must be between 1 and 65535")); + mockMvc.perform(json(put("/api/client/server"), "{}")) + .andExpect(status().isBadRequest()); + mockMvc.perform(json(put("/api/client/server"), "not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Request body is missing or malformed")); + + verify(stateService, never()).setActiveServer(any()); + } + + @Test + void reportsWhenNoServerAnswersAtTheGivenAddress() throws Exception { + when(discoveryService.resolveServerByIp("10.0.0.2", null)).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No MediaGarrd server found at 10.0.0.2")); + } + + @Test + void rejectsInvalidPickupIntervals() throws Exception { + when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new IllegalArgumentException("Pickup interval must be a positive duration")); + + mockMvc.perform(json(put("/api/client/pickup-interval"), "{\"interval\":\"PT0S\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Pickup interval must be a positive duration")); + } + + @Test + void unknownPickupTasksAreNotFound() throws Exception { + when(backupPickupService.pickupProgress("gone")).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + + mockMvc.perform(get("/api/client/pickup/progress/gone")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Pickup task not found: gone")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java new file mode 100644 index 0000000..de33936 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java @@ -0,0 +1,139 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@WebMvcTest(controllers = ServerConfigController.class) +class ServerConfigControllerTest { + + private static final String SERVER = "http://server:8080"; + private static final ServiceDto RADARR = new ServiceDto("radarr", List.of("/srv/radarr")); + private static final String RADARR_JSON = """ + {"name": "radarr", "paths": ["/srv/radarr"]} + """; + + @Autowired + MockMvc mockMvc; + + @MockBean + ClientStateService stateService; + + @MockBean + ServerApiService serverApiService; + + @BeforeEach + void setUp() { + when(stateService.requireActiveServer()).thenReturn(SERVER); + } + + @Test + void returnsServerConfig() throws Exception { + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 4, Duration.ofHours(6))); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/backups")) + .andExpect(jsonPath("$.retentionCount").value(4)) + .andExpect(jsonPath("$.backupInterval").value("PT6H")); + } + + @Test + void updatesConfigAndScheduleTogether() throws Exception { + when(serverApiService.updateServerConfig(SERVER, "/new", 3)).thenReturn(new ServerConfigDto("/new", 3, Duration.ofHours(6))); + when(serverApiService.updateServerSchedule(SERVER, Duration.ofMinutes(90))) + .thenReturn(new ServerStatusDto(true, false, 3, Duration.ofMinutes(90))); + + mockMvc.perform(json(put("/api/client/server-config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 3, \"backupInterval\": \"PT90M\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/new")) + .andExpect(jsonPath("$.retentionCount").value(3)) + .andExpect(jsonPath("$.backupInterval").value("PT1H30M")); + } + + @Test + void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { + when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + + mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupInterval").value("PT6H")); + + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); + } + + @Test + void forwardsServiceChanges() throws Exception { + when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); + when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); + when(serverApiService.updateService(SERVER, "old name", RADARR)).thenReturn(RADARR); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("radarr")) + .andExpect(jsonPath("$[0].paths[0]").value("/srv/radarr")); + mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("radarr")); + mockMvc.perform(json(put("/api/client/services/old name"), RADARR_JSON)) + .andExpect(status().isOk()); + mockMvc.perform(delete("/api/client/services/radarr")) + .andExpect(status().isNoContent()); + + verify(serverApiService).removeService(SERVER, "radarr"); + } + + @Test + void rejectsRequestsWithoutAnActiveServer() throws Exception { + when(stateService.requireActiveServer()) + .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected")); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No active MediaGarrd server selected")); + + verify(serverApiService, never()).listServices(anyString()); + } + + @Test + void reportsAnUnreachableServer() throws Exception { + when(serverApiService.serverConfig(SERVER)).thenThrow(new ResourceAccessException("Connection refused")); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.error").value("MediaGarrd server is unreachable")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java new file mode 100644 index 0000000..4c39aa4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java @@ -0,0 +1,199 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +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.junit.jupiter.api.io.TempDir; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +class BackupPickupServiceTest { + + private static final String SERVER = "http://server:8080"; + private static final BackupDto LATEST = new BackupDto("b2", "b2-media-backup.zip", 4, Instant.EPOCH); + private static final BackupDto OLDER = new BackupDto("b1", "b1-media-backup.zip", 4, Instant.EPOCH); + + @TempDir + Path downloads; + + private final ClientStateService state = mock(ClientStateService.class); + private final ServerApiService api = mock(ServerApiService.class); + private final MutableClock clock = new MutableClock(); + private BackupPickupService pickup; + + @BeforeEach + void setUp() { + Configuration configuration = new Configuration(); + configuration.setDownloadDirectory(downloads.toString()); + when(state.requireActiveServer()).thenReturn(SERVER); + when(state.getPickupInterval()).thenReturn(Duration.ofHours(1)); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); + pickup = new BackupPickupService(configuration, state, api, clock); + } + + @AfterEach + void tearDown() { + pickup.shutdown(); + } + + @Test + void downloadsTheLatestBackup() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> invocation.getArgument(2)); + + PickupStartDto started = pickup.startPickupLatestTask(); + PickupProgressDto progress = awaitFinished(started.taskId()); + + assertEquals("COMPLETED", progress.status()); + assertEquals(downloads.resolve("b2-media-backup.zip").toString(), progress.savedPath()); + } + + @Test + void reusesTheRunningTaskForTheSameBackup() throws Exception { + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + release.await(5, TimeUnit.SECONDS); + return invocation.getArgument(2); + }); + + PickupStartDto first = pickup.startPickupLatestTask(); + PickupStartDto second = pickup.startPickupByIdTask("b2"); + release.countDown(); + awaitFinished(first.taskId()); + + assertEquals(first.taskId(), second.taskId()); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reusesAnExistingDownload() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + + PickupProgressDto progress = pickup.pickupProgress(pickup.startPickupByIdTask("b1").taskId()); + + assertEquals("COMPLETED", progress.status()); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reportsDownloadFailures() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("disk full")); + + PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertEquals("disk full", progress.error()); + } + + @Test + void forgetsFinishedTasksAfterTheRetentionPeriod() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + String taskId = pickup.startPickupByIdTask("b1").taskId(); + + clock.advance(BackupPickupService.FINISHED_TASK_RETENTION.plusSeconds(1)); + pickup.startPickupByIdTask("b1"); + + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress(taskId)); + } + + @Test + void rejectsUnknownBackupsAndTasks() { + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupByIdTask("missing")); + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress("missing")); + when(api.listBackups(SERVER)).thenReturn(List.of()); + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupLatestTask()); + } + + @Test + void refusesFileNamesThatLeaveTheDownloadDirectory() { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); + + assertThrows(IllegalArgumentException.class, () -> pickup.startPickupLatestTask()); + } + + @Test + void scheduledPickupKeepsOnlyTheLatestAutomaticDownload() throws IOException { + Files.write(downloads.resolve("b1-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[3]); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + + clock.advance(Duration.ofHours(2)); + pickup.scheduledPickup(); + + assertEquals(List.of("b2-media-backup-AD.zip", "b2-media-backup.zip"), fileNames()); + } + + private PickupProgressDto awaitFinished(String taskId) throws InterruptedException { + for (int attempt = 0; attempt < 200; attempt++) { + PickupProgressDto progress = pickup.pickupProgress(taskId); + if (progress.status().equals("COMPLETED") || progress.status().equals("FAILED")) { + return progress; + } + Thread.sleep(10); + } + throw new AssertionError("Pickup task " + taskId + " did not finish"); + } + + private List fileNames() throws IOException { + try (var files = Files.list(downloads)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } + } + + private static void assertStatus(HttpStatus status, Runnable action) { + assertEquals(status, assertThrows(ResponseStatusException.class, action::run).getStatusCode()); + } + + private static final class MutableClock extends Clock { + private Instant now = Instant.parse("2026-10-26T00:00:00Z"); + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java new file mode 100644 index 0000000..0fb435d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -0,0 +1,103 @@ +package wellatleastitried.mediagarrdclient.service; + +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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.server.ResponseStatusException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.Configuration; + +class ClientStateServiceTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @TempDir + Path tempDir; + + private final Configuration configuration = new Configuration(); + + @BeforeEach + void setUp() { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + } + + @Test + void persistsAndLoadsState() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + state.setActiveServer("http://b:8080"); + state.setPickupInterval(Duration.ofMinutes(30)); + + ClientStateService reloaded = new ClientStateService(configuration, MAPPER); + assertEquals("http://b:8080", reloaded.getActiveServer()); + assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); + assertEquals(List.of("http://a:8080", "http://b:8080"), reloaded.getKnownServers()); + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void keepsTheActiveServerWhenARescanDoesNotFindIt() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + + state.updateKnownServers(List.of("http://b:8080")); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://b:8080", "http://a:8080"), state.getKnownServers()); + } + + @Test + void selectsTheFirstDiscoveredServerWhenNoneIsActive() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + state.updateKnownServers(List.of("http://b:8080", "http://b:8080", "http://c:8080")); + + assertEquals("http://b:8080", state.getActiveServer()); + assertEquals(List.of("http://b:8080", "http://c:8080"), state.getKnownServers()); + } + + @Test + void rejectsNonPositivePickupIntervals() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(Duration.ZERO)); + assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(null)); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + } + + @Test + void requiresAnActiveServer() { + assertThrows(ResponseStatusException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); + } + + @Test + void startsWithDefaultsWhenTheStateFileIsUnreadable() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{not json"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertNull(state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + } + + private List fileNames() { + try (var files = Files.list(tempDir)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java new file mode 100644 index 0000000..bd3f4ba --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -0,0 +1,123 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +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.RestClientResponseException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.api.ApiExceptionHandler; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; + +class ServerApiServiceTest { + + private record Exchange(String method, String path, String body) { + } + + private final List exchanges = new ArrayList<>(); + private final ServerApiService service = new ServerApiService(); + private HttpServer server; + private String serverUrl; + private int status = 200; + 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(); + serverUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void sendsConfigUpdatesWithOmittedFieldsAsNull() { + response = "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": \"PT6H\"}"; + + ServerConfigDto config = service.updateServerConfig(serverUrl, null, 5); + + assertEquals(new ServerConfigDto("/backups", 5, Duration.ofHours(6)), config); + assertEquals(new Exchange("PUT", "/api/v1/config", "{\"backupLocation\":null,\"retentionCount\":5}"), exchanges.getFirst()); + } + + @Test + void sendsScheduleAsIsoDuration() { + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H30M\"}"; + + assertEquals(Duration.ofMinutes(90), service.updateServerSchedule(serverUrl, Duration.ofMinutes(90)).backupInterval()); + assertEquals(new Exchange("PUT", "/api/v1/schedule", "{\"backupInterval\":\"PT1H30M\"}"), exchanges.getFirst()); + } + + @Test + void encodesServiceNamesInPaths() { + ServiceDto radarr = new ServiceDto("radarr", List.of("/srv/radarr")); + response = "{\"name\": \"radarr\", \"paths\": [\"/srv/radarr\"]}"; + + assertEquals(radarr, service.updateService(serverUrl, "old name", radarr)); + status = 204; + service.removeService(serverUrl, "radarr"); + + assertEquals("/api/v1/services/old%20name", exchanges.get(0).path()); + assertEquals(new Exchange("DELETE", "/api/v1/services/radarr", ""), exchanges.get(1)); + } + + @Test + void forwardsTheServerErrorMessageAndStatus() { + status = 409; + response = "{\"error\": \"Service already exists: radarr\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, + () -> service.addService(serverUrl, new ServiceDto("radarr", List.of("/srv/radarr")))); + ResponseEntity forwarded = new ApiExceptionHandler().serverRejected(e); + + assertEquals(HttpStatus.CONFLICT, forwarded.getStatusCode()); + assertEquals(Map.of("error", "Service already exists: radarr"), forwarded.getBody()); + } + + @Test + void fallsBackToTheStatusWhenTheServerSendsNoMessage() { + status = 502; + response = "Bad Gateway"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.serverConfig(serverUrl)); + + assertEquals(Map.of("error", "MediaGarrd server responded with 502"), new ApiExceptionHandler().serverRejected(e).getBody()); + } + + 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)); + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (status == 204) { + exchange.sendResponseHeaders(204, -1); + } else { + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java new file mode 100644 index 0000000..fd527b3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -0,0 +1,165 @@ +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; + +class ServerDiscoveryServiceTest { + + private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; + + private final Configuration configuration = new Configuration(); + private final ClientStateService state = mock(ClientStateService.class); + private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, new ObjectMapper()); + private HttpServer mediaGarrd; + private HttpServer otherApp; + + @BeforeEach + void startServers() throws IOException { + mediaGarrd = serve(HEALTH); + otherApp = serve("ok"); + } + + @AfterEach + void stopServers() { + mediaGarrd.stop(0); + otherApp.stop(0); + discovery.shutdown(); + } + + @Test + void resolvesTheGivenPort() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1", port(mediaGarrd))); + } + + @Test + void readsThePortFromTheAddress() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1:" + port(mediaGarrd), null)); + } + + @Test + void scansEveryPortWhenTheGivenPortIsNotAMediaGarrdServer() { + long start = System.nanoTime(); + + Optional found = discovery.resolveServerByIp("127.0.0.1", port(otherApp)); + + assertTrue(found.isPresent(), "no MediaGarrd server found by the port scan"); + assertNotEquals(url(otherApp), found.get()); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 15, "full port scan took too long"); + } + + @Test + void preferredServerIsResolvedFromConfiguration() { + configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); + + assertEquals(Optional.of("http://localhost:" + port(mediaGarrd)), discovery.resolvePreferredServer()); + } + + @Test + void connectsThePreferredServerOnlyWhileNoneIsSelected() { + configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + + discovery.connectPreferredServer(); + when(state.getActiveServer()).thenReturn("http://other:38471"); + discovery.connectPreferredServer(); + + verify(state, times(1)).setActiveServer(url(mediaGarrd)); + } + + @Test + void givesUpQuicklyOnAnUnreachableHost() { + long start = System.nanoTime(); + + assertEquals(Optional.empty(), discovery.resolveServerByIp("192.0.2.1", 8123)); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 3, "unreachable host was port scanned"); + } + + @Test + void ignoresUnresolvableHosts() { + assertEquals(Optional.empty(), discovery.resolveServerByIp("no-such-host.invalid", null)); + assertEquals(Optional.empty(), discovery.resolveServerByIp(" ", null)); + } + + @Test + void rejectsHealthResponsesThatAreNotFromAMediaGarrdServer() throws IOException { + HttpServer lookalike = serve("{\"status\":\"UP\"}"); + try { + InetAddress loopback = InetAddress.getLoopbackAddress(); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(lookalike)))); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(otherApp)))); + assertTrue(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(mediaGarrd)))); + } finally { + lookalike.stop(0); + } + } + + @ParameterizedTest + @CsvSource({"24, 254, 192.168.1.1, 192.168.1.254", "16, 254, 192.168.1.1, 192.168.1.254", "30, 2, 192.168.1.77, 192.168.1.78", "32, 2, 192.168.1.77, 192.168.1.78"}) + void listsTheHostsOfTheLocalSubnet(int prefix, int count, String first, String last) throws IOException { + List hosts = ServerDiscoveryService.subnetHosts((Inet4Address) InetAddress.getByName("192.168.1.77"), prefix); + + assertEquals(count, hosts.size()); + assertEquals(first, hosts.getFirst().getHostAddress()); + assertEquals(last, hosts.getLast().getHostAddress()); + } + + @ParameterizedTest + @CsvSource(value = {"192.168.1.5, 192.168.1.5, null", "192.168.1.5:9000, 192.168.1.5, 9000", "http://server:38471/, server, 38471", "[::1]:8080, ::1, 8080"}, nullValues = "null") + void parsesHostsWithOptionalPorts(String input, String host, Integer port) { + assertEquals(new HostInput(host, port), ServerDiscoveryService.parseHost(input)); + } + + @Test + void rejectsInputWithoutAHost() { + assertNull(ServerDiscoveryService.parseHost("http://")); + } + + private static HttpServer serve(String body) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + return server; + } + + private static int port(HttpServer server) { + return server.getAddress().getPort(); + } + + private static String url(HttpServer server) { + return "http://127.0.0.1:" + port(server); + } +} diff --git a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java deleted file mode 100644 index df656cc..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -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; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -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 wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@WebMvcTest(controllers = ClientController.class) -class ClientControllerTest { - - @Autowired - MockMvc mockMvc; - - @MockBean - ClientStateService stateService; - - @MockBean - ServerDiscoveryService discoveryService; - - @MockBean - ServerApiService serverApiService; - - @MockBean - BackupPickupService backupPickupService; - - @Test - void statusEndpointReturnsState() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - - mockMvc.perform(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.activeServer").value("http://server:8080")); - } - - @Test - void discoverEndpointUpdatesState() throws Exception { - when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(post("/api/client/discover")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.knownServers[0]").value("http://server:8080")); - } - - @Test - void listBackupsReturnsServerData() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); - - mockMvc.perform(get("/api/client/backups")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value("id")); - } - - @Test - void setServerEndpointAcceptsUpdate() throws Exception { - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(put("/api/client/server") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"serverUrl\":\"http://server:8080\"}")) - .andExpect(status().isOk()); - } - - @Test - void pickupEndpointReturnsPath() throws Exception { - when(backupPickupService.pickupLatest()).thenReturn(Path.of("/tmp/latest.zip")); - - mockMvc.perform(post("/api/client/pickup")) - .andExpect(status().isOk()); - } -} diff --git a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java deleted file mode 100644 index e4ef030..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrdclient.Configuration; - -class ClientStateServiceTest { - - @TempDir - Path tempDir; - - @Test - void persistsAndLoadsState() { - Configuration cfg = new Configuration(); - cfg.setStateFile(tempDir.resolve("state.json").toString()); - cfg.setPickupInterval(Duration.ofHours(12)); - - ClientStateService state = new ClientStateService(cfg); - state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); - state.setActiveServer("http://b:8080"); - state.setPickupInterval(Duration.ofMinutes(30)); - - ClientStateService reloaded = new ClientStateService(cfg); - assertEquals("http://b:8080", reloaded.getActiveServer()); - assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); - assertEquals(2, reloaded.getKnownServers().size()); - } -} From 256faeb643a615516b0fa4d3d11925e331997942 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 10:35:04 -0600 Subject: [PATCH 2/6] Update LICENSE file --- LICENSE | 695 ++------------------------------------------------------ 1 file changed, 21 insertions(+), 674 deletions(-) diff --git a/LICENSE b/LICENSE index f288702..ba28e3b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2026 Jackson Swindell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 84a1c34e4f3e6b02f6823a354a14b1ab30de4b99 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 17:59:18 -0600 Subject: [PATCH 3/6] Change license from GPLv3 to MIT --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35e5bed..ce4c774 100644 --- a/README.md +++ b/README.md @@ -44,4 +44,4 @@ docker compose up --build -d Downloaded backups and the client state live in the mounted `./data/client` volumes and are kept. ## License -[GPLv3](./LICENSE) +[MIT](./LICENSE) From 1d9fe2539942941f610b594df09e5f26bc3eef52 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Wed, 11 Nov 2026 18:32:42 -0600 Subject: [PATCH 4/6] Update alerting, cleaning up refresh rates for certain panels. --- CHANGELOG | 65 +- Makefile | 1 + README.md | 30 + build.gradle.kts | 6 + .../mediagarrdclient/Configuration.java | 36 + .../api/ApiExceptionHandler.java | 19 +- .../api/ClientController.java | 32 +- .../api/ClientEventsController.java | 46 + .../mediagarrdclient/api/Endpoints.java | 4 +- .../mediagarrdclient/dto/CheckState.java | 9 + .../dto/ConnectionStatusDto.java | 7 - .../mediagarrdclient/dto/DashboardState.java | 13 + .../mediagarrdclient/dto/HealthSummary.java | 6 + .../mediagarrdclient/dto/LinkState.java | 8 + .../dto/VersionStatusDto.java | 13 + .../mediagarrdclient/dto/VersionsDto.java | 3 + .../service/BackupRunTimeoutException.java | 8 + .../mediagarrdclient/service/ClientEvent.java | 4 + .../service/ClientEventBroadcaster.java | 198 +++++ .../service/ClientStateService.java | 120 ++- .../service/DashboardService.java | 426 ++++++++++ .../service/RequestTimeouts.java | 37 + .../mediagarrdclient/service/SemVer.java | 78 ++ .../service/ServerApiService.java | 49 +- .../service/ServerDiscoveryService.java | 63 +- .../service/ServerEventStreamService.java | 375 +++++++++ .../service/UpdateCheckService.java | 190 +++++ .../service/VersionService.java | 151 ++++ src/main/resources/application.yml | 8 + src/main/resources/static/css/mediagarrd.css | 22 + src/main/resources/static/index.html | 23 +- src/main/resources/static/js/api.js | 2 +- src/main/resources/static/js/backups.js | 20 +- src/main/resources/static/js/connection.js | 97 ++- .../resources/static/js/dashboard-model.js | 87 ++ src/main/resources/static/js/events.js | 91 ++ src/main/resources/static/js/main.js | 91 +- .../resources/static/js/pickup-interval.js | 5 + src/main/resources/static/js/reachability.js | 29 + src/main/resources/static/js/versions.js | 27 + src/main/resources/static/js/view-model.js | 74 ++ .../mediagarrdclient/MediaGarrdTest.java | 22 + .../api/ClientControllerTest.java | 48 +- .../api/ClientEventsControllerTest.java | 74 ++ .../service/ClientEventBroadcasterTest.java | 262 ++++++ .../service/ClientStateServiceTest.java | 121 +++ .../service/DashboardServiceTest.java | 783 ++++++++++++++++++ .../mediagarrdclient/service/SemVerTest.java | 66 ++ .../service/ServerApiServiceTest.java | 112 ++- .../service/ServerDiscoveryServiceTest.java | 159 +++- .../service/ServerEventStreamServiceTest.java | 451 ++++++++++ .../service/UpdateCheckServiceTest.java | 322 +++++++ .../service/VersionServiceTest.java | 236 ++++++ src/test/js/dashboard-model.test.mjs | 202 +++++ src/test/js/reachability.test.mjs | 77 ++ src/test/js/view-model.test.mjs | 142 ++++ 56 files changed, 5491 insertions(+), 159 deletions(-) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/CheckState.java delete mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/HealthSummary.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/LinkState.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/VersionStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/VersionsDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunTimeoutException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientEvent.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/RequestTimeouts.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/SemVer.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/VersionService.java create mode 100644 src/main/resources/static/js/dashboard-model.js create mode 100644 src/main/resources/static/js/events.js create mode 100644 src/main/resources/static/js/reachability.js create mode 100644 src/main/resources/static/js/versions.js create mode 100644 src/main/resources/static/js/view-model.js create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java create mode 100644 src/test/js/dashboard-model.test.mjs create mode 100644 src/test/js/reachability.test.mjs create mode 100644 src/test/js/view-model.test.mjs 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…'); +}); From 176b187d96e646879d67b0a105f05f3ed3fe8126 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 12 Nov 2026 17:16:27 -0600 Subject: [PATCH 5/6] Consolidate unecessary information from README. --- README.md | 67 +++++++++--------------------------------------- docs/API.md | 36 ++++++++++++++++++++++++++ docs/network.md | 23 +++++++++++++++++ docs/settings.md | 20 +++++++++++++++ docs/testing.md | 19 ++++++++++++++ 5 files changed, 110 insertions(+), 55 deletions(-) create mode 100644 docs/API.md create mode 100644 docs/network.md create mode 100644 docs/settings.md create mode 100644 docs/testing.md diff --git a/README.md b/README.md index f2141dd..6b80349 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,18 @@ # Client -This is the official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +The official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). It is a web dashboard that connects to a [MediaGarrd Server](https://github.com/MediaGarrd/Server), shows its status live, runs and downloads backups, and changes the server's configuration. + +Full documentation is on the [MediaGarrd website](https://mediagarrd.github.io/MediaGarrd/). + +## Docs +- [settings.md](./docs/settings.md): every environment variable and its default. +- [network.md](./docs/network.md): how the client finds servers on the network. +- [API.md](./docs/API.md): every HTTP endpoint and what it returns. +- [testing.md](./docs/testing.md): running the Java and browser tests. ## Requirements -- Docker with Compose v2 (`docker compose ...`) -- A running [MediaGarrd Server](https://github.com/MediaGarrd/Server) that has finished its first-time setup +- Docker with Compose v2 +- A MediaGarrd Server that has finished its first-time setup ## Installation ```bash @@ -14,64 +22,13 @@ cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` -Then open `http://:8081`. - -The defaults in `docker-compose.yml` work as-is. To change them before the first start: -- **Port:** change both `CLIENT_PORT` and the `ports` mapping (default `8081`). -- **Where downloaded backups are stored on the host:** change the left side of the `./data/client/downloads` volume. -- **Where the client keeps its state on the host:** change the left side of the `./data/client/state` volume. This holds the selected server, known servers, and pickup interval, so keep it on persistent storage. -- **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 -"Scan Local Network" checks every address of the networks the client is attached to, on `MEDIAGARRD_SERVER_PORT`, `38471`, `8080`, and `80`, and lists every MediaGarrd server that answers. "Connect by IP" also accepts `:`, and scans every port of the host when the server is not on one of those ports. - -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). +Then open `http://:8081` and connect to your server by IP or with "Scan Local Network". To connect automatically, add `MEDIAGARRD_SERVER_IP=` to `environment` in `docker-compose.yml`. ## Updating ```bash git pull docker compose up --build -d ``` -Downloaded backups and the client state live in the mounted `./data/client` volumes and are kept. ## License [MIT](./LICENSE) diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..5cf2628 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,36 @@ +# Client API + +All endpoints are under `/api/client`. Endpoints that act on the connected server need a server to be selected. Errors are returned as `{"error": "..."}` with a matching status code. + +## Dashboard +| Endpoint | Returns | +|---|---| +| `GET /status` | The selected server, the known servers, and the pickup interval. | +| `GET /dashboard` | The dashboard state: selected and known servers, connection state, run state, the server's schedule and retention, and both versions. | +| `GET /events` | A Server-Sent Events stream that starts with the dashboard state and then pushes each change to it. | + +## Servers +| Endpoint | Returns | +|---|---| +| `POST /discover` | The servers found by scanning the local network. | +| `PUT /server` | The client status after selecting a server by URL, or by IP and optional port. | + +## Backups +| Endpoint | Returns | +|---|---| +| `GET /backups` | The connected server's archives. | +| `POST /backups/run` | An empty `200` once the connected server finishes a backup, or `504` if it takes longer than the run timeout. | +| `POST /pickup` | A task id and the archive's details after starting a download of the newest archive. | +| `POST /pickup/{id}` | A task id and the archive's details after starting a download of one archive. | +| `GET /pickup/progress/{taskId}` | A download's status, bytes written, total size, and saved path. | +| `PUT /pickup-interval` | The client status after changing how often the newest archive is downloaded automatically. | + +## Server configuration +| Endpoint | Returns | +|---|---| +| `GET /server-config` | The connected server's backup location, number of backups to keep, and time between backups. | +| `PUT /server-config` | The connected server's updated configuration. | +| `GET /services` | The connected server's services with their host paths. | +| `POST /services` | The service added to the connected server, with `201`. | +| `PUT /services/{name}` | The updated service on the connected server. | +| `DELETE /services/{name}` | An empty `204` once the service is removed from the connected server. | diff --git a/docs/network.md b/docs/network.md new file mode 100644 index 0000000..deaa7e1 --- /dev/null +++ b/docs/network.md @@ -0,0 +1,23 @@ +# Finding servers on the network + +The client can find MediaGarrd servers in three ways. + +## Scan Local Network +"Scan Local Network" on the Dashboard checks every address of the networks the client is attached to. +- It tries `MEDIAGARRD_SERVER_PORT` first, then `38471`, `8080`, and `80`. +- An address counts as a MediaGarrd server only if it answers `GET /api/v1/health` like one. +- Networks larger than a `/24` are scanned as the `/24` around the client's own address. +- Loopback, Docker, VPN, and other virtual interfaces are skipped. +- A scan gives up after 20 seconds. +- Every server it finds is added to Known Servers. + +## Connect by IP +"Connect by IP" accepts `` or `:`. It tries the given port and the common ports above first. If none of them answer, it scans every port from 1024 to 65535 on that host. + +## Connecting automatically +Set `MEDIAGARRD_SERVER_IP=` (or `:`) in the client's `environment`. While no server is selected, the client tries that address every few seconds and connects as soon as it answers. + +## Docker networking +With the default Docker networking the client only sees its container network. A scan then finds servers running on the same host, but not on other machines. To reach those: +- Use "Connect by IP" or `MEDIAGARRD_SERVER_IP`. +- Or add `network_mode: host` to the client's service in `docker-compose.yml`, and remove its `ports` mapping, so the scan covers your LAN. diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..ba8ef22 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,20 @@ +# Settings + +Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for example `PT12H`. + +| Variable | Default | What it does | +|---|---|---| +| `CLIENT_PORT` | `8081` | The port of the web dashboard. Change the `ports` mapping to match. | +| `CLIENT_PICKUP_INTERVAL` | `PT12H` | How often the newest archive is downloaded automatically. Only the initial value: once it is saved in the dashboard, the stored value is used. | +| `CLIENT_BACKUP_RUN_TIMEOUT` | `PT6H` | How long "Run Backup Now" waits for the server to finish. Minimum `PT1M`. If a run takes longer, the dashboard shows an error, but the backup keeps running on the server. | +| `MEDIAGARRD_SERVER_IP` | (none) | A server to connect to automatically, as `` or `:`. See [network.md](./network.md). | +| `MEDIAGARRD_SERVER_PORT` | `38471` | The server port tried first by "Scan Local Network" and "Connect by IP". | +| `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Client` | The GitHub repository checked for new releases. | +| `MEDIAGARRD_GITHUB_API_URL` | `https://api.github.com` | The GitHub API used for the release check. | +| `MEDIAGARRD_UPDATE_CHECK_INTERVAL` | `PT24H` | How often the release check runs. Minimum `PT1H`. | +| `CLIENT_STATE_FILE` | `/var/lib/mediagarrd/client/state.json` | Where the client keeps its selected server, known servers, and pickup interval, inside the container. | +| `CLIENT_DOWNLOAD_DIRECTORY` | `/var/lib/mediagarrd/downloads` | Where downloaded archives are saved, inside the container. | + +To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: +- `./data/client/downloads`: downloaded archives. +- `./data/client/state`: the client's state. Keep it on persistent storage. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..3b33b9a --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,19 @@ +# Testing + +`make test` runs both the Java tests and the browser tests. + +## Browser tests +The browser tests cover the pure modules in `src/main/resources/static/js`: +- `dashboard-model.js`: how events change the dashboard state, and when the archive list reloads. +- `view-model.js`: how the connection state, known servers, and versions are rendered. +- `reachability.js`: when the client counts as unreachable. + +They need Node 20.19 or newer and have no dependencies. Run them on their own from the repository root: +```bash +node --test src/test/js/*.test.mjs +``` + +## Java tests +```bash +./gradlew test +``` From 6dbd1adb7e7d2d19fa592342994cedb7685e2d63 Mon Sep 17 00:00:00 2001 From: Jackson Swindell Date: Thu, 19 Nov 2026 15:36:13 -0600 Subject: [PATCH 6/6] Added auth, code quality refactors --- .dockerignore | 9 + CHANGELOG | 62 ++ CLAUDE.md | 1 + Dockerfile | 14 +- README.md | 9 +- build.gradle.kts | 7 +- docker-entrypoint.sh | 67 ++ docs/API.md | 43 +- docs/https.md | 94 +++ docs/network.md | 13 +- docs/settings.md | 29 +- docs/testing.md | 9 +- .../mediagarrdclient/MediaGarrd.java | 2 +- ...uration.java => MediaGarrdProperties.java} | 29 +- .../api/ApiExceptionHandler.java | 101 ++- .../mediagarrdclient/api/AuthController.java | 144 +++++ .../mediagarrdclient/api/BodyLimitFilter.java | 129 ++++ .../api/ClientController.java | 38 +- .../ClientEventBroadcaster.java | 54 +- .../api/ClientEventsController.java | 13 +- .../mediagarrdclient/api/CsrfCheck.java | 53 ++ .../api/PairingController.java | 39 ++ .../mediagarrdclient/api/PublicEndpoint.java | 13 + .../api/RequestTooLargeException.java | 10 + .../api/SecurityHeadersFilter.java | 33 + .../api/ServerConfigController.java | 20 +- .../mediagarrdclient/api/SessionGate.java | 71 +++ .../mediagarrdclient/api/WebMvcConfig.java | 20 + .../api/WebhookController.java | 52 ++ .../mediagarrdclient/dto/AuthStatusDto.java | 4 + .../mediagarrdclient/dto/DashboardState.java | 3 +- .../mediagarrdclient/dto/PairRequest.java | 9 + .../mediagarrdclient/dto/PairingCodeDto.java | 6 + .../dto/PairingResultDto.java | 4 + .../mediagarrdclient/dto/PairingState.java | 8 + .../mediagarrdclient/dto/PasswordRequest.java | 9 + .../mediagarrdclient/dto/UnpairResultDto.java | 4 + .../dto/WebhookStatusDto.java | 4 + .../mediagarrdclient/dto/WebhookTestDto.java | 4 + .../dto/WebhookUpdateRequest.java | 9 + .../{api => protocol}/Endpoints.java | 9 +- .../service/BackupPickupService.java | 257 ++++++-- .../service/BackupRunFailedException.java | 8 + .../service/BackupWatcher.java | 109 ++++ .../service/ClientEventPublisher.java | 6 + .../service/ClientPairingService.java | 133 ++++ .../service/ClientStateService.java | 255 ++++++-- .../service/CoalescedRefresh.java | 63 ++ .../service/ConfirmationRefusedException.java | 8 + .../ConfirmationUnavailableException.java | 8 + .../service/ConflictException.java | 8 + .../service/DashboardEvents.java | 31 + .../service/DashboardService.java | 311 ++++----- .../service/DownloadFailedException.java | 12 + .../service/InvalidRequestException.java | 8 + .../service/LinkStateMachine.java | 69 ++ .../service/LoginAttempts.java | 131 ++++ .../service/NoBackupsException.java | 8 + .../service/NotFoundException.java | 8 + .../service/OwnerOnlyFiles.java | 50 ++ .../service/PairingRequiredException.java | 8 + .../service/PairingStatus.java | 56 ++ .../service/PasswordService.java | 158 +++++ .../service/PickupSchedule.java | 49 ++ .../mediagarrdclient/service/QuietFiles.java | 25 + .../service/ReconnectPolicy.java | 47 ++ .../service/ServerApiService.java | 349 ++++++++-- .../service/ServerDiscoveryService.java | 107 +++- .../service/ServerEventStreamService.java | 264 ++++---- .../service/ServerRedirectException.java | 17 + .../service/ServerSelectionService.java | 39 ++ .../mediagarrdclient/service/ServerTls.java | 175 +++++ .../service/ServerTokens.java | 9 + .../mediagarrdclient/service/ServerUrls.java | 55 ++ .../service/ServiceNames.java | 18 + .../service/SessionService.java | 188 ++++++ .../mediagarrdclient/service/SseReader.java | 88 +++ .../service/StoredPairing.java | 9 + .../service/UpdateCheckService.java | 15 +- .../service/UpstreamResponseException.java | 8 + src/main/resources/application.yml | 6 + src/main/resources/static/css/mediagarrd.css | 108 +++- src/main/resources/static/index.html | 187 ++++-- src/main/resources/static/js/api.js | 69 +- src/main/resources/static/js/auth-model.js | 17 + src/main/resources/static/js/auth.js | 151 +++++ src/main/resources/static/js/backups.js | 102 ++- src/main/resources/static/js/busy.js | 11 + src/main/resources/static/js/connection.js | 2 + .../resources/static/js/dashboard-model.js | 11 +- src/main/resources/static/js/events.js | 17 +- src/main/resources/static/js/format.js | 29 +- src/main/resources/static/js/main.js | 106 +++- src/main/resources/static/js/notify.js | 3 + src/main/resources/static/js/pairing-model.js | 31 + src/main/resources/static/js/pairing.js | 94 +++ .../resources/static/js/pickup-interval.js | 7 +- src/main/resources/static/js/server-config.js | 13 +- src/main/resources/static/js/services.js | 20 +- src/main/resources/static/js/settings.js | 9 +- src/main/resources/static/js/view-model.js | 22 +- src/main/resources/static/js/webhook.js | 103 +++ .../mediagarrdclient/MediaGarrdTest.java | 74 --- .../api/ApiExceptionHandlerTest.java | 130 ++++ .../api/AuthControllerConcurrencyTest.java | 151 +++++ .../api/AuthGateFullContextTest.java | 333 ++++++++++ .../api/ClientApiGoldenTest.java | 251 ++++++++ .../api/ClientControllerTest.java | 121 ++-- .../ClientEventBroadcasterTest.java | 85 +-- .../api/ClientEventsControllerTest.java | 28 +- .../mediagarrdclient/api/CsrfCheckTest.java | 94 +++ .../FirstVisitPasswordFullContextTest.java | 108 ++++ .../api/PairingControllerTest.java | 76 +++ .../api/RecordingEmitter.java | 52 ++ .../api/RunningServerTest.java | 163 +++++ .../api/ServerConfigControllerTest.java | 102 +-- .../mediagarrdclient/api/TestCsrfHeader.java | 16 + .../mediagarrdclient/api/TestSession.java | 25 + .../api/WebhookControllerTest.java | 128 ++++ .../mediagarrdclient/golden/Fixtures.java | 23 + .../service/BackupPickupServiceTest.java | 169 +++-- .../service/ClientPairingServiceTest.java | 360 +++++++++++ .../service/ClientStateServiceTest.java | 255 +++++++- .../service/DashboardServiceTest.java | 240 ++++--- .../service/LoginAttemptsTest.java | 191 ++++++ .../service/MutableClock.java | 43 ++ .../service/PasswordServiceTest.java | 152 +++++ .../service/PickupScheduleTest.java | 68 ++ .../service/ReconnectPolicyTest.java | 58 ++ .../service/RecordingPublisher.java | 68 ++ .../service/ScheduledPickupTest.java | 599 ++++++++++++++++++ .../mediagarrdclient/service/SemVerTest.java | 7 +- .../service/ServerApiServiceTest.java | 403 +++++++++++- .../service/ServerDiscoveryServiceTest.java | 94 ++- .../service/ServerEventStreamServiceTest.java | 468 ++++++++++++-- .../service/ServerPayloadGoldenTest.java | 174 +++++ .../service/ServerTlsTest.java | 202 ++++++ .../service/ServerUrlsTest.java | 34 + .../service/ServiceNamesTest.java | 23 + .../service/SessionServiceTest.java | 104 +++ .../service/SseReaderTest.java | 97 +++ .../StateFileMissingFieldsGoldenTest.java | 80 +++ .../service/StateFilesGoldenTest.java | 91 +++ .../service/UpdateCheckServiceTest.java | 46 +- .../service/VersionServiceTest.java | 41 +- src/test/js/api.test.mjs | 112 ++++ src/test/js/auth-model.test.mjs | 29 + src/test/js/busy.test.mjs | 50 ++ src/test/js/dashboard-model.test.mjs | 27 +- src/test/js/events.test.mjs | 154 +++++ src/test/js/format.test.mjs | 87 +++ src/test/js/notify.test.mjs | 44 ++ src/test/js/pairing-model.test.mjs | 51 ++ src/test/js/view-model.test.mjs | 40 +- src/test/js/webhook.test.mjs | 238 +++++++ .../resources/golden/client/auth-status.json | 1 + src/test/resources/golden/client/backups.json | 1 + .../resources/golden/client/dashboard.json | 1 + .../resources/golden/client/error-4xx.json | 1 + .../resources/golden/client/pairing-code.json | 1 + .../client/pairing-result-deferred.json | 1 + .../golden/client/pairing-result.json | 1 + .../golden/client/pickup-progress.json | 1 + .../resources/golden/client/pickup-start.json | 1 + .../golden/client/server-config.json | 1 + .../resources/golden/client/services.json | 1 + src/test/resources/golden/client/status.json | 1 + .../golden/client/unpair-result.json | 1 + .../golden/client/webhook-status.json | 1 + .../resources/golden/client/webhook-test.json | 1 + .../golden/client/webhook-unset.json | 1 + src/test/resources/golden/disk/password.json | 5 + .../golden/disk/state-no-interval.json | 11 + .../golden/disk/state-null-interval.json | 12 + src/test/resources/golden/disk/state.json | 18 + src/test/resources/golden/server/backups.json | 1 + src/test/resources/golden/server/config.json | 1 + .../resources/golden/server/error-4xx.json | 1 + .../golden/server/error-spring-default.json | 1 + .../golden/server/health-public.json | 1 + .../golden/server/health-status.json | 1 + .../golden/server/pair-response.json | 1 + .../resources/golden/server/pairing-code.json | 1 + .../resources/golden/server/services.json | 1 + src/test/resources/golden/server/version.json | 1 + .../golden/server/webhook-status.json | 1 + .../resources/golden/server/webhook-test.json | 1 + 187 files changed, 11186 insertions(+), 1283 deletions(-) create mode 100644 CLAUDE.md create mode 100755 docker-entrypoint.sh create mode 100644 docs/https.md rename src/main/java/wellatleastitried/mediagarrdclient/{Configuration.java => MediaGarrdProperties.java} (79%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java rename src/main/java/wellatleastitried/mediagarrdclient/{service => api}/ClientEventBroadcaster.java (77%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java rename src/main/java/wellatleastitried/mediagarrdclient/{api => protocol}/Endpoints.java (58%) create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java create mode 100644 src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java create mode 100644 src/main/resources/static/js/auth-model.js create mode 100644 src/main/resources/static/js/auth.js create mode 100644 src/main/resources/static/js/busy.js create mode 100644 src/main/resources/static/js/pairing-model.js create mode 100644 src/main/resources/static/js/pairing.js create mode 100644 src/main/resources/static/js/webhook.js delete mode 100644 src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java rename src/test/java/wellatleastitried/mediagarrdclient/{service => api}/ClientEventBroadcasterTest.java (81%) create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java create mode 100644 src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java create mode 100644 src/test/js/api.test.mjs create mode 100644 src/test/js/auth-model.test.mjs create mode 100644 src/test/js/busy.test.mjs create mode 100644 src/test/js/events.test.mjs create mode 100644 src/test/js/format.test.mjs create mode 100644 src/test/js/notify.test.mjs create mode 100644 src/test/js/pairing-model.test.mjs create mode 100644 src/test/js/webhook.test.mjs create mode 100644 src/test/resources/golden/client/auth-status.json create mode 100644 src/test/resources/golden/client/backups.json create mode 100644 src/test/resources/golden/client/dashboard.json create mode 100644 src/test/resources/golden/client/error-4xx.json create mode 100644 src/test/resources/golden/client/pairing-code.json create mode 100644 src/test/resources/golden/client/pairing-result-deferred.json create mode 100644 src/test/resources/golden/client/pairing-result.json create mode 100644 src/test/resources/golden/client/pickup-progress.json create mode 100644 src/test/resources/golden/client/pickup-start.json create mode 100644 src/test/resources/golden/client/server-config.json create mode 100644 src/test/resources/golden/client/services.json create mode 100644 src/test/resources/golden/client/status.json create mode 100644 src/test/resources/golden/client/unpair-result.json create mode 100644 src/test/resources/golden/client/webhook-status.json create mode 100644 src/test/resources/golden/client/webhook-test.json create mode 100644 src/test/resources/golden/client/webhook-unset.json create mode 100644 src/test/resources/golden/disk/password.json create mode 100644 src/test/resources/golden/disk/state-no-interval.json create mode 100644 src/test/resources/golden/disk/state-null-interval.json create mode 100644 src/test/resources/golden/disk/state.json create mode 100644 src/test/resources/golden/server/backups.json create mode 100644 src/test/resources/golden/server/config.json create mode 100644 src/test/resources/golden/server/error-4xx.json create mode 100644 src/test/resources/golden/server/error-spring-default.json create mode 100644 src/test/resources/golden/server/health-public.json create mode 100644 src/test/resources/golden/server/health-status.json create mode 100644 src/test/resources/golden/server/pair-response.json create mode 100644 src/test/resources/golden/server/pairing-code.json create mode 100644 src/test/resources/golden/server/services.json create mode 100644 src/test/resources/golden/server/version.json create mode 100644 src/test/resources/golden/server/webhook-status.json create mode 100644 src/test/resources/golden/server/webhook-test.json diff --git a/.dockerignore b/.dockerignore index dbeb426..5b09deb 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,12 @@ .git +.jj +.claude +.env +ref +bin +.settings +.classpath +.project .github .vscode build @@ -15,4 +23,5 @@ secrets LICENSE README.md CHANGELOG +docker-compose.yml docker-compose.example.yml diff --git a/CHANGELOG b/CHANGELOG index 500ed68..ff7948a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,67 @@ # CHANGELOG +Everything in this file is part of version 0.1.0, the first release. Entries are grouped by the date they were made. + +## 11-24-26 +- Switching the active server between two known servers that are not paired now updates the dashboard (state and event stream) straight away; before, it kept showing the previous server until something else refreshed it +- Events forwarded from the server to the dashboard are re-serialized as compact JSON on one line, so a server cannot add its own event fields to the dashboard stream +- A backup whose file name does not end in `.zip` (or ends in `.part`) is refused before anything is downloaded: a manual pickup answers `400`, an automatic one is skipped and logged as a warning +- After a successful automatic pickup, the client removes the earlier `*-media-backup-AD.zip` copies of the older archives the active server still lists, not only the one before the latest. Newer copies, copies of archives the server no longer lists (for example from another server), your own copies (`*-media-backup.zip`) and other files are never touched + +## 11-22-26 +- A state file the client cannot read (wrong owner or permissions, for example after switching to `user:`) now stops startup with a message naming the file and the UID, instead of being moved aside as `.corrupt-*` and dropping every pairing. Only a file that is really malformed is moved aside +- The pickup interval is limited to 365 days: `PUT /api/client/pickup-interval` answers `400` above that, the dashboard field takes at most 525600 minutes and checks it, and an out-of-range value in the state file or `CLIENT_PICKUP_INTERVAL` is ignored with a warning in favour of the default of 12 hours +- A server that has no backups yet is reported once at INFO, then only at DEBUG on each retry, instead of a WARN every time +- The image has a `HEALTHCHECK` that asks the dashboard's open `/api/auth/status` on `CLIENT_PORT` +- Documented that with `network_mode: host` `CLIENT_PORT` must stay at 1024 or above and that `cap_drop: ALL` needs `CHOWN`, `SETUID` and `SETGID` (or `user:`), and that the `MEDIAGARRD_SERVER_CA` file must be readable by UID 1000 or `PUID` +- The container no longer runs Java as root. It starts as root only to give UID 1000 (or `PUID` and `PGID`) ownership of the state and download folders and of the client's own files in them (the state file with its `.tmp` and `.corrupt-*` copies, `password.json`, and `*-media-backup.zip`, `*-media-backup-AD.zip` and their `.part` files), then runs the client as that user. Other files in your folders are left alone, and the state folder is never changed recursively. Existing installs keep working without a manual `chown`; with `user:` in Compose the entrypoint skips the ownership step, so the folders must already belong to that user. `PUID=0` keeps running as root. The base image is pinned to `eclipse-temurin:21.0.13_9-jre` +- A scan merges the servers it finds into Known Servers instead of replacing the list: servers already known (for example an `https://` one outside the LAN) stay, new ones are added, and the active server stays selected +- Server Configuration checks the backup interval (15 minutes to 365 days, as the server does; the field takes 0.25 to 8760 hours) before sending anything, and `PUT /api/client/server-config` answers `400` for an interval outside that range without changing the location or retention either +- Clearer messages: a server that has not paired this client no longer produces "Connect to a server" hints, Server Configuration says to pair on the Dashboard, a proxy timeout reads as one instead of "POST ... failed (504)", the rejected-token note leads with a pairing code, and disabled buttons are muted +- Pairing confirms itself: after the server issues a token the client makes one authenticated request (`GET /api/v1/health`) to confirm it, retried up to 3 times after a network error or a 502, 503 or 504. The client stores the token first and discards it only when the server refuses the confirmation (a `401` or a reply that is not a confirmation, reported as a `400` or `502`), so the same PIN or pairing code can be entered again; any other failure keeps the token, answers `paired: true` with a new `note` saying the server confirms it on the next connection, and a lost reply can no longer leave the server with a client the Client has forgotten. Pairing while a stored token still works is refused with `409` (unpair first), and pairing and unpairing no longer run at the same time +- The warnings after unpairing no longer point at the server's `/config` page (it is disabled after setup); they say to remove the client with `DELETE /api/v1/clients/{id}` on the server +- Works with the Server's confirm-on-first-use pairing (Server 11-22-26) and with earlier 11-19-26 servers, where the confirmation request simply succeeds + +## 11-21-26 +- Server Configuration has a Failure Notifications panel for the server's optional failure webhook: Save, Clear and Send Test, showing only `Configured: https://host` (the URL is a secret and is never shown or pre-filled). New proxy endpoints `GET` and `PUT /api/client/notifications/webhook` and `POST /api/client/notifications/webhook/test`; a `429` from the server's test cooldown is passed on with its `Retry-After` +- Fixed the missing space between the note and the first field of the set-password form +- Routine reads (`GET /api/client/server-config` and `/services`, and the event stream's "subscribing" and "no event stream" lines, and a preferred server that does not answer) are logged at DEBUG instead of INFO, so polling no longer fills the log; changes, pairing, downloads and errors still log at INFO or WARN +- The pickup schedule survives restarts. The client keeps the time of the last successful pickup of the latest archive (`lastPickupAt` in the state file) and the next pickup is due one interval after it. After a restart an overdue pickup runs on the first check once the client is paired with the active server and the server answers; one that is not overdue waits for its original due time. Changing the pickup interval recomputes the due time from the last pickup +- A pickup that fails or cannot reach the server is retried after 1, 2, 5, 10 and then every 15 minutes, instead of after a full interval. A client that is not paired waits quietly. A scheduled pickup and a manual download of the same archive no longer download it twice +- Switching the active server clears the last pickup time, so the first pickup from the new server is due at once instead of waiting for the old server's schedule. If the pickup time cannot be saved to the state file, the client backs off instead of retrying every minute, and a backward clock jump delays a retry by at most 15 minutes +- A download that finishes after the active server was switched no longer sets the new server's last pickup time. A scheduled pickup records its time before its task reports completed +- Incomplete `.part` files left behind by a crash or restart are deleted on startup and before each pickup, unless they belong to a transfer in progress +- On a phone-width screen the dashboard and Server Configuration no longer scroll sideways: grid columns, form rows and notes shrink to the screen, and the archives and services tables scroll inside their panel +- Server Configuration puts Backup Settings alone in the left column, with Add Service and then Failure Notifications stacked in the right column (in that order under Backup Settings on a narrow screen) + +## 11-19-26 +- The client pairs with the server. Selecting a server that has no stored token shows a pairing form in the Server Status panel: enter the `Pairing PIN` from the server's logs or a pairing code, and the client calls the server's `POST /api/v1/pair` and keeps the token per server address in its state file (readable by its owner only). The token is never logged, shown, or sent to the browser +- Every request to the server (API calls, the event stream, backup downloads, scheduled pickups, and the health check once paired) sends `Authorization: Bearer `. Requests to the server no longer follow redirects, so the token cannot be replayed elsewhere; a redirect is reported with the address it points to +- When the server rejects the token (`401`) the client answers `502` with `"pairing": "required"`, the dashboard says the token was rejected and offers to pair again, and the event stream stops retrying until the client is paired again. The dashboard state has a new `pairing` field and event (`NONE`, `PAIRED`, `REQUIRED`, `REJECTED`) +- New endpoints: `POST /api/client/pairing`, `POST /api/client/pairing/code` (a one-time code that pairs another client) and `DELETE /api/client/pairing` (revokes this client on the server and forgets the token, also when the server cannot be reached) +- The dashboard has a password. The first visitor sets it (at least 8 characters), or `CLIENT_PASSWORD` sets it and disables the form; `CLIENT_RESET_PASSWORD=true` removes a stored one on start. It is stored as a salted PBKDF2-HMAC-SHA256 hash (600,000 iterations) in `password.json` next to the state file. Sessions use an `HttpOnly`, `SameSite=Strict` cookie (`Secure` over HTTPS or with `X-Forwarded-Proto: https`) and end after 12 hours idle or 7 days; failed logins from one address are delayed from 5 seconds up to 5 minutes (`429`) +- Every `/api/client` endpoint, including `GET /events`, now needs the session; only the page, its assets and `/api/auth/status`, `login`, `set-password` and `logout` do not. Changing requests are refused when the browser marks them as cross-site. Scripts log in with `POST /api/auth/login` and keep the cookie +- An address typed with `https://` (in "Connect by IP" or `MEDIAGARRD_SERVER_IP`) keeps its scheme and defaults to port 443; no port scan is done for it. Plain `ip` and `ip:port` behave as before +- `MEDIAGARRD_SERVER_CA` trusts extra certificate authorities, or a self-signed certificate, for connections to the server, next to the system ones. The GitHub update check is unaffected. The client refuses to start if the file cannot be read +- Server addresses are normalized (lowercase scheme and host, default port and trailing slash dropped); stored addresses are migrated when the state is loaded. Tokens are tied to the exact address, so switching from `http://:38471` to `https://` needs pairing again +- The client needs a server from 11-19-26 or later; older servers have no pairing +- Changing requests without `Sec-Fetch-Site` or `Origin` headers must send `X-MediaGarrd-Request: 1`. A login attempt is checked one at a time per address and a few at a time overall, and all addresses together get 30 password checks a minute (a successful login gives its check back); when they are used up, logins get `429` with `Retry-After` until the next check is free +- Every response carries `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, so the dashboard cannot be embedded in another page +- An unexpected failure (HTTP 500) answers with `{"error": "Internal error"}`; the details are only in the log +- When the server accepts the token again after rejecting it, the event stream restarts at most once every 5 minutes, and only if the stream itself was rejected +- Added [docs/https.md](./docs/https.md) with nginx and Caddy examples +- Selecting a server by URL now checks that a MediaGarrd server answers at that address before it is stored (`400` with `No MediaGarrd server found at ` otherwise). Servers the client already knows are not checked again +- Request bodies on `/api` are limited to 64 KiB, also when sent chunked (`413` with `{"error": "Request body is too large"}`). A pairing PIN or code is limited to 64 characters and the client name to 64. Service names in the path must be letters, digits, `.`, `_` or `-` (at most 64). A line or event on the server's event stream is limited to 1 MiB +- Every response now also carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer` and a `Content-Security-Policy` of `default-src 'self'` (plus `frame-ancestors 'none'`); `/api` responses carry `Cache-Control: no-store` +- Every error answer is `{"error": "..."}`. Unexpected failures and failures reported by the server with a 5xx status carry no detail (`Internal error`, or `MediaGarrd server responded with `); the details are only in the log. The one exception is a failed `POST /api/client/backups/run`, which answers `500` with the run's failure reason from the server (the server does the same for that call), because the dashboard shows it. The messages of failed downloads in the progress of a pickup no longer include file paths +- Downloaded archives are saved with owner-only permissions (`0600`, new directories `0700`). A download that receives no data for 60 seconds fails +- Pairing while this client still holds a working token is refused with `409` (unpair first), and nothing is revoked on the server. `DELETE /pairing` answers `{"serverRevoked", "warning"}`; `warning` says why the server was not told, or is `null` +- A request that the server answers with `401` marks the pairing as rejected at once, without waiting for the next health check +- The live event stream of the browser ends when its session ends (logout, a new password, expiry) +- A `state.json` that cannot be read is moved to `state.json.corrupt-` and logged as an error instead of being overwritten. Changes to the state are written to disk before they take effect, so a failed save no longer leaves the client and its file out of step +- The scheduled pickup no longer runs on the shared scheduler thread. A pickup whose archive name leaves the download directory no longer leaves a stuck task behind, and the scheduled pickup never deletes an archive it did not download itself +- The release link of the update check must point to `https://github.com/`; otherwise it is built from the tag + ## 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 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Dockerfile b/Dockerfile index 3be39cf..9b86100 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,8 +3,18 @@ WORKDIR /workspace COPY . . RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all -FROM eclipse-temurin:21-jre +FROM eclipse-temurin:21.0.13_9-jre WORKDIR /app +RUN set -eux; \ + if getent passwd 1000 >/dev/null; then userdel "$(getent passwd 1000 | cut -d: -f1)"; fi; \ + if getent group 1000 >/dev/null; then groupdel "$(getent group 1000 | cut -d: -f1)"; fi; \ + groupadd --gid 1000 mediagarrd; \ + useradd --uid 1000 --gid 1000 --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin mediagarrd; \ + mkdir -p /var/lib/mediagarrd/client /var/lib/mediagarrd/downloads; \ + chown -R 1000:1000 /var/lib/mediagarrd COPY --from=build /workspace/build/libs/*.jar app.jar +COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/mediagarrd-entrypoint EXPOSE 8081 -ENTRYPOINT ["java", "-jar", "/app/app.jar"] +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 CMD ["sh", "-c", "curl -fsS -o /dev/null \"http://127.0.0.1:${CLIENT_PORT:-8081}/api/auth/status\""] +ENTRYPOINT ["/usr/local/bin/mediagarrd-entrypoint"] +CMD ["java", "-jar", "/app/app.jar"] diff --git a/README.md b/README.md index 6b80349..1f6d51b 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,16 @@ Full documentation is on the [MediaGarrd website](https://mediagarrd.github.io/M ## Docs - [settings.md](./docs/settings.md): every environment variable and its default. +- [https.md](./docs/https.md): HTTPS with nginx or Caddy, and self-signed certificates. - [network.md](./docs/network.md): how the client finds servers on the network. - [API.md](./docs/API.md): every HTTP endpoint and what it returns. - [testing.md](./docs/testing.md): running the Java and browser tests. ## Requirements - Docker with Compose v2 -- A MediaGarrd Server that has finished its first-time setup +- A MediaGarrd Server from 11-19-26 or later that has finished its first-time setup. Older servers have no pairing, so this client cannot use them + +The dashboard has a password and the client pairs with each server. Whoever opens a new dashboard first can choose its password, so do it right after installing, or set `CLIENT_PASSWORD`. Beyond a trusted network, put both behind HTTPS: see [https.md](./docs/https.md). ## Installation ```bash @@ -22,7 +25,9 @@ cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` -Then open `http://:8081` and connect to your server by IP or with "Scan Local Network". To connect automatically, add `MEDIAGARRD_SERVER_IP=` to `environment` in `docker-compose.yml`. +Then open `http://:8081` and choose a dashboard password (or set `CLIENT_PASSWORD`). Connect to your server by IP or with "Scan Local Network", then pair: enter the `Pairing PIN` that the server's setup page shows after Finish Setup, which it also prints in its logs (`docker logs mediagarrd-server 2>&1 | grep "Pairing PIN"`). To connect automatically, add `MEDIAGARRD_SERVER_IP=` to `environment` in `docker-compose.yml`. + +The container runs the client as UID 1000, not as root. On first start it gives that user ownership of the mounted state and downloads folders (`./data/client/state` and `./data/client/downloads` in the example) and of the client's own files in them, so existing installs keep working. To use another owner, add `PUID` and `PGID` to `environment` in `docker-compose.yml` (see [settings](./docs/settings.md)). ## Updating ```bash diff --git a/build.gradle.kts b/build.gradle.kts index 3a1bf34..58d8f94 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,7 @@ plugins { java - id("org.springframework.boot") version "3.3.5" - id("io.spring.dependency-management") version "1.1.6" + id("org.springframework.boot") version "4.1.3" + id("io.spring.dependency-management") version "1.1.7" } version = "0.1.0" @@ -13,7 +13,8 @@ repositories { dependencies { testImplementation("org.springframework.boot:spring-boot-starter-test") testRuntimeOnly("org.junit.platform:junit-platform-launcher") - implementation("org.springframework.boot:spring-boot-starter-web") + testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test") + implementation("org.springframework.boot:spring-boot-starter-webmvc") implementation("org.springframework.boot:spring-boot-starter") } diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 0000000..649574c --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,67 @@ +#!/bin/sh +set -eu + +PUID="${PUID:-1000}" +PGID="${PGID:-1000}" + +for value in "$PUID" "$PGID"; do + case "$value" in + ''|*[!0-9]*) + echo "PUID and PGID must be numbers, got PUID='$PUID' PGID='$PGID'" >&2 + exit 1 + ;; + esac + if [ "${#value}" -gt 10 ] || [ "$value" -gt 4294967294 ]; then + echo "PUID and PGID must be at most 4294967294, got PUID='$PUID' PGID='$PGID'" >&2 + exit 1 + fi +done + +export HOME=/tmp + +warn() { + echo "Warning: $*" >&2 +} + +prepare() { + state_file="${CLIENT_STATE_FILE:-/var/lib/mediagarrd/client/state.json}" + state_dir="$(dirname "$state_file")" + state_base="$(basename "$state_file")" + download_dir="${CLIENT_DOWNLOAD_DIRECTORY:-/var/lib/mediagarrd/downloads}" + + mkdir -p "$state_dir" "$download_dir" || warn "could not create $state_dir or $download_dir" + + for dir in "$state_dir" "$download_dir"; do + if [ "$dir" = "/" ]; then + warn "refusing to change the owner of /" + else + echo "Giving $PUID:$PGID ownership of $dir and the client's own files in it" >&2 + chown -h "$PUID:$PGID" "$dir" || warn "could not change the owner of $dir" + fi + done + + if [ -d "$state_dir" ] && [ "$state_dir" != "/" ]; then + find "$state_dir" -maxdepth 1 -type f -links 1 \ + \( -name "$state_base" -o -name "$state_base.tmp" -o -name "$state_base.corrupt-*" \ + -o -name password.json -o -name password.json.tmp \) \ + -exec chown -h "$PUID:$PGID" {} + || warn "could not change the owner of the client's files in $state_dir" + fi + + if [ -d "$download_dir" ] && [ "$download_dir" != "/" ]; then + find "$download_dir" -maxdepth 1 -type f -links 1 \ + \( -name '*-media-backup.zip' -o -name '*-media-backup-AD.zip' -o -name '*-media-backup*.zip.part' \) \ + -exec chown -h "$PUID:$PGID" {} + || warn "could not change the owner of the client's archives in $download_dir" + fi +} + +uid="$(id -u)" +if [ "$uid" -eq 0 ] && [ "$PUID" -ne 0 ]; then + prepare + if ! command -v setpriv >/dev/null 2>&1; then + echo "setpriv is not available in this image, cannot drop privileges" >&2 + exit 1 + fi + exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups --no-new-privs -- "$@" +fi + +exec "$@" diff --git a/docs/API.md b/docs/API.md index 5cf2628..d44ddb4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,27 +1,49 @@ # Client API -All endpoints are under `/api/client`. Endpoints that act on the connected server need a server to be selected. Errors are returned as `{"error": "..."}` with a matching status code. +Endpoints are under `/api/client` and `/api/auth`. Endpoints that act on the connected server need a server to be selected. Errors are returned as `{"error": "..."}` with a matching status code. A `5xx` caused by the client itself, or reported by the server, carries no detail (`{"error": "Internal error"}` or `{"error": "MediaGarrd server responded with "}`), with one exception: a failed `POST /api/client/backups/run` answers `500` with the run's failure reason in `error`, because the dashboard shows it. The documented `502`, `503` and `504` answers below keep their messages. A request body over 64 KiB, declared or chunked, is refused with `413`. + +## Login +Everything under `/api/client`, including `GET /events`, needs the dashboard session cookie (`mg_session`, `HttpOnly`, `SameSite=Strict`, `Secure` over HTTPS or when the proxy sends `X-Forwarded-Proto: https`). Without it the client answers `401` with `{"error": "Login required", "login": "required"}`. Requests that change something (anything but GET) are refused with `403` when a browser marks them as cross-site: `Sec-Fetch-Site` must be `same-origin`, or `Origin` must match the `Host` (or `X-Forwarded-Host`) header. A request with neither header must carry `X-MediaGarrd-Request: 1`; the dashboard sends it on every call, and scripts must add it to every non-GET request. + +| Endpoint | Returns | +|---|---| +| `GET /api/auth/status` | `{"passwordSet", "passwordFromEnvironment", "authenticated"}`. No session needed. | +| `POST /api/auth/login` | `{"authenticated": true}` and the session cookie for body `{"password": "..."}`. `401` for a wrong password, `409` when no password is set, `429` with `Retry-After` while the source address is locked out after repeated failures, while another attempt from it is still being checked, when several passwords are already being checked, or when all addresses together have used up their 30 password checks a minute. | +| `POST /api/auth/set-password` | Sets the first password (body `{"password": "..."}`, 8 to 256 characters) and signs in. `409` when a password already exists or `CLIENT_PASSWORD` is set. | +| `POST /api/auth/logout` | An empty `204` and an expired cookie. | + +A headless script logs in with `curl -c jar -H 'X-MediaGarrd-Request: 1' -H 'Content-Type: application/json' -d '{"password":"..."}' http://:8081/api/auth/login` and sends `-b jar -H 'X-MediaGarrd-Request: 1'` on every later non-GET request. + +## Pairing +The client keeps one token per server address. Tokens never appear in any response. When the server has no token for the selected address, or the server rejects it (`401`), a request that needs the server is answered with `502` and `{"error": "...", "pairing": "required"}`. `GET /dashboard` and the `snapshot` event carry `pairing`: `NONE` (no server), `PAIRED`, `REQUIRED` (no token stored) or `REJECTED` (the server refused the stored token); the `pairing` event carries `{"state": ...}`. + +| Endpoint | Returns | +|---|---| +| `POST /pairing` | `{"paired": true, "name": "...", "note": null}` after pairing with the selected server. Answers `409` while this client holds a stored token that the server still accepts (the client probes it with `GET /api/v1/health`); unpair first. A pair or unpair request waits while another one is running. A stored token the server refuses (`401`) is replaced. Body `{"pin": "", "name": ""}`. The client pairs, stores the token, then confirms it with one authenticated `GET /api/v1/health` on the server (retried up to 3 times after a network error or a 502, 503 or 504). A `401` on the confirmation, or a reply that is not a confirmation, discards the token and is answered with a `400` (or `502`), so the same PIN or code can be tried again. Any other failure keeps the token and answers `{"paired": true, "name": "...", "note": "..."}`, where `note` says the server will confirm it on the next connection; `note` is `null` after a confirmed pairing. A wrong PIN or code is a `400`; the server's `403` (pairing closed), `409` (setup not finished) and `429` (locked) are passed on with its message. | +| `POST /pairing/code` | `{"code": "XXXXX-XXXXX", "expiresAt": "..."}`: a one-time code, valid for 10 minutes, that pairs another client. Shown only in this response. | +| `DELETE /pairing` | `{"serverRevoked": true/false, "warning": null or "..."}`. Revokes this client's token on the server and forgets it locally. It waits while a pair request is running. `{"serverRevoked": false, "warning": "..."}` when the server could not be told (unreachable, token rejected, or no client id stored): the token is forgotten locally anyway and `warning` says the server may still list this client. `warning` is `null` when `serverRevoked` is `true`. | + ## Dashboard | Endpoint | Returns | |---|---| | `GET /status` | The selected server, the known servers, and the pickup interval. | | `GET /dashboard` | The dashboard state: selected and known servers, connection state, run state, the server's schedule and retention, and both versions. | -| `GET /events` | A Server-Sent Events stream that starts with the dashboard state and then pushes each change to it. | +| `GET /events` | A Server-Sent Events stream that starts with the dashboard state and then pushes each change to it, including `pairing`. | ## Servers | Endpoint | Returns | |---|---| | `POST /discover` | The servers found by scanning the local network. | -| `PUT /server` | The client status after selecting a server by URL, or by IP and optional port. | +| `PUT /server` | The client status after selecting a server by URL, or by IP and optional port. A URL that is not already known is checked first: if no MediaGarrd server answers there the client answers `400`. An address that starts with `https://` keeps its scheme and, without a port, uses 443; no port scan is done for it. | ## Backups | Endpoint | Returns | |---|---| | `GET /backups` | The connected server's archives. | | `POST /backups/run` | An empty `200` once the connected server finishes a backup, or `504` if it takes longer than the run timeout. | -| `POST /pickup` | A task id and the archive's details after starting a download of the newest archive. | -| `POST /pickup/{id}` | A task id and the archive's details after starting a download of one archive. | +| `POST /pickup` | A task id and the archive's details after starting a download of the newest archive. `400` if the server gives the archive a file name that does not end in `.zip` or ends in `.part`. | +| `POST /pickup/{id}` | A task id and the archive's details after starting a download of one archive. `400` for the same file name check. | | `GET /pickup/progress/{taskId}` | A download's status, bytes written, total size, and saved path. | | `PUT /pickup-interval` | The client status after changing how often the newest archive is downloaded automatically. | @@ -29,8 +51,17 @@ All endpoints are under `/api/client`. Endpoints that act on the connected serve | Endpoint | Returns | |---|---| | `GET /server-config` | The connected server's backup location, number of backups to keep, and time between backups. | -| `PUT /server-config` | The connected server's updated configuration. | +| `PUT /server-config` | The connected server's updated configuration. A `backupInterval` shorter than 15 minutes or longer than 365 days is refused with `400` (`Backup interval must be between 15 minutes and 365 days`) before anything is sent to the server, so the location and retention are not changed either. | | `GET /services` | The connected server's services with their host paths. | | `POST /services` | The service added to the connected server, with `201`. | | `PUT /services/{name}` | The updated service on the connected server. | | `DELETE /services/{name}` | An empty `204` once the service is removed from the connected server. | + +## Failure webhook +Proxies the connected server's failure webhook (see the server's API.md), which the server calls when a backup fails or only partly succeeds. The full URL is a secret, so it is never returned: only whether one is set and its `scheme://host[:port]`. A write needs the same `X-MediaGarrd-Request: 1` header as the other writes. + +| Endpoint | Returns | +|---|---| +| `GET /notifications/webhook` | `{"configured": true, "target": "https://discord.com"}` or `{"configured": false, "target": null}`. | +| `PUT /notifications/webhook` | The same shape after saving. Body `{"url": "https://..."}`; an empty string clears the webhook. An invalid URL is a `400` with the server's message. | +| `POST /notifications/webhook/test` | `{"delivered": false, "status": 404, "error": "Webhook answered 404"}` after the server sends a test message (`status` is the receiver's 2xx code when delivered and `null` only when no reply came, and `error` is `null` when delivered). A test less than 10 seconds after the last one is a `429` with the server's message and its `Retry-After` header. `400` when no webhook is set. | diff --git a/docs/https.md b/docs/https.md new file mode 100644 index 0000000..d07176b --- /dev/null +++ b/docs/https.md @@ -0,0 +1,94 @@ +# HTTPS + +The Client dashboard and the Server both speak plain HTTP. To use HTTPS, put a reverse proxy in front of each. This matters because the dashboard password, the session cookie, the pairing PIN and the pairing tokens travel in plain text over HTTP. On a network you do not control, use HTTPS. The Server has its own page: [Server docs/https.md](https://github.com/MediaGarrd/Server/blob/main/docs/https.md). Read it too: it covers the Server side of this setup. + +## 1. Keep the plain ports private +`docker-compose.example.yml` publishes the Client with `"8081:8081"`. Remove that mapping so the plain port is not reachable from outside, and put the Client and the proxy on a shared Docker network. The proxy reaches it by container name. The Server does the same with its `"38471:38471"` mapping. + +```yaml +services: + mediagarrd-client: + build: + context: . + dockerfile: Dockerfile + container_name: mediagarrd-client + environment: + - CLIENT_PORT=8081 + - CLIENT_PICKUP_INTERVAL=PT12H + - MEDIAGARRD_SERVER_PORT=38471 + - MEDIAGARRD_SERVER_IP=https://mediagarrd.example.com + volumes: + - "./data/client/downloads:/var/lib/mediagarrd/downloads" + - "./data/client/state:/var/lib/mediagarrd/client" + networks: + - proxy + restart: unless-stopped + +networks: + proxy: + name: proxy +``` + +Run the proxy on the same network (`proxy`) and send traffic to `mediagarrd-client:8081`. + +## 2. Serve the dashboard at the root of a domain +The dashboard uses absolute paths (`/js/main.js`, `/api/client/...`). It must be served at the root of a domain or subdomain, for example `https://client.example.com`. It does not work under a subpath such as `https://example.com/mediagarrd/`. + +The proxy must pass the `Host` header on unchanged (or send `X-Forwarded-Host`) and, for the cookie, tell the Client the scheme with `X-Forwarded-Proto: https`. The Client uses the first to accept changing requests from the dashboard and the second to mark the session cookie `Secure`. Caddy does both by default; nginx needs the two `proxy_set_header` lines below. + +### Caddy +``` +client.example.com { + reverse_proxy mediagarrd-client:8081 { + flush_interval -1 + } +} +``` +`flush_interval -1` sends the live event stream (`/api/client/events`) through immediately. + +### nginx +```nginx +server { + listen 443 ssl http2; + server_name client.example.com; + + ssl_certificate /etc/ssl/mediagarrd/fullchain.pem; + ssl_certificate_key /etc/ssl/mediagarrd/privkey.pem; + + location / { + proxy_pass http://mediagarrd-client:8081; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} +``` +On nginx 1.25.1 or newer, `http2 on;` as its own directive replaces the `http2` parameter on `listen`; the parameter still works there but is deprecated. `proxy_buffering off` lets the event stream through. The long timeouts matter for "Run Backup Now", which holds a request open until the backup finishes (up to `CLIENT_BACKUP_RUN_TIMEOUT`, default 6 hours), so raise them if your backups take longer. + +Behind a proxy the Client sees every visitor as coming from the proxy, so the failed-login delay is shared by all of them. + +## 3. Serve the Server +Follow the Server's page for its proxy (`https://mediagarrd.example.com` in the examples). Large backup downloads and backup runs need long timeouts there too: nginx `proxy_read_timeout` and `proxy_send_timeout`, and `proxy_buffering off`. Caddy sets no time limit. + +## 4. Connect the Client to the HTTPS Server +Type the address with its scheme in "Connect by IP", or set `MEDIAGARRD_SERVER_IP=https://mediagarrd.example.com`. The scheme is kept, and without a port the Client uses 443 and checks only that address; it does not scan ports. "Scan Local Network" only looks for plain HTTP servers. + +A token is tied to the exact address it was paired on. Switching from `http://:38471` to `https://mediagarrd.example.com` means pairing again with a PIN or a pairing code. + +The Client does not follow redirects when it talks to the Server, so a proxy rule that redirects HTTP to HTTPS makes an `http://` address fail. For a Server that is already selected the dashboard reports the address the redirect points to; while connecting ("Connect by IP" or `MEDIAGARRD_SERVER_IP`) you only see that no server was found. Use the `https://` address. + +### Certificates from your own authority or self-signed +A certificate from a public authority (Let's Encrypt, Caddy's automatic certificates, Tailscale) needs nothing extra. For a private or self-signed certificate, give the Client the certificate authority, or the self-signed certificate itself, as a PEM file: + +```yaml + environment: + - MEDIAGARRD_SERVER_CA=/etc/mediagarrd/ca.pem + volumes: + - "./ca.pem:/etc/mediagarrd/ca.pem:ro" +``` +- The file may hold several certificates. They are trusted in addition to the system ones, only for connections to the Server; the GitHub update check is not affected. +- The file must be readable by the user the Client runs as: UID 1000, or your `PUID`. Mode `0644` works; a `0600` file owned by root does not. The Client does not start if the file cannot be read or holds no certificate, and says why. +- The host name is still checked. If you reach the Server by IP address, the certificate needs that IP in its Subject Alternative Names (for example `-addext "subjectAltName=IP:192.168.1.10"` with `openssl req`). diff --git a/docs/network.md b/docs/network.md index deaa7e1..7ef4053 100644 --- a/docs/network.md +++ b/docs/network.md @@ -9,15 +9,20 @@ The client can find MediaGarrd servers in three ways. - Networks larger than a `/24` are scanned as the `/24` around the client's own address. - Loopback, Docker, VPN, and other virtual interfaces are skipped. - A scan gives up after 20 seconds. -- Every server it finds is added to Known Servers. +- Every server it finds is added to Known Servers. Servers that are already known stay in the list, even when the scan does not find them again. ## Connect by IP -"Connect by IP" accepts `` or `:`. It tries the given port and the common ports above first. If none of them answer, it scans every port from 1024 to 65535 on that host. +"Connect by IP" accepts ``, `:`, or an `https://` address such as `https://garrd.example.com`. For an `https://` address the client uses the default port (443) unless you give one, checks only that address, and does not scan ports. The scan of the local network always uses plain HTTP. For a plain address it tries the given port and the common ports above first. If none of them answer, it scans every port from 1024 to 65535 on that host. ## Connecting automatically -Set `MEDIAGARRD_SERVER_IP=` (or `:`) in the client's `environment`. While no server is selected, the client tries that address every few seconds and connects as soon as it answers. +Set `MEDIAGARRD_SERVER_IP=` (or `:`, or `https://`) in the client's `environment`. While no server is selected, the client tries that address every few seconds and connects as soon as it answers. ## Docker networking With the default Docker networking the client only sees its container network. A scan then finds servers running on the same host, but not on other machines. To reach those: - Use "Connect by IP" or `MEDIAGARRD_SERVER_IP`. -- Or add `network_mode: host` to the client's service in `docker-compose.yml`, and remove its `ports` mapping, so the scan covers your LAN. +- Or add `network_mode: host` to the client's service in `docker-compose.yml`, and remove its `ports` mapping, so the scan covers your LAN. Keep `CLIENT_PORT` at 1024 or above in that case: the client does not run as root and cannot bind a lower port. If you also use `cap_drop: ALL`, keep `CHOWN`, `SETUID` and `SETGID`, or set `user:` instead (see [settings.md](./settings.md)). + +## Pairing +Finding a server does not give access to it. Without a token the server's health check only says whether it is healthy and its backup interval; everything else needs the token you get by pairing. See [settings.md](./settings.md). + +For HTTPS, see [https.md](./https.md). diff --git a/docs/settings.md b/docs/settings.md index ba8ef22..19da442 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -5,16 +5,37 @@ Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for | Variable | Default | What it does | |---|---|---| | `CLIENT_PORT` | `8081` | The port of the web dashboard. Change the `ports` mapping to match. | -| `CLIENT_PICKUP_INTERVAL` | `PT12H` | How often the newest archive is downloaded automatically. Only the initial value: once it is saved in the dashboard, the stored value is used. | +| `CLIENT_PICKUP_INTERVAL` | `PT12H` | How often the newest archive is downloaded automatically. Between 1 second and 365 days; a value outside that range is ignored with a warning and the default is used. Only the initial value: once it is saved in the dashboard, the stored value is used. The time of the last successful pickup is kept in the state file, so a restart does not reset the schedule: a pickup that is overdue runs on the first check (every minute) once the client has an active server, a stored pairing, and the server answers; otherwise it runs at the original due time. A pickup that cannot run is retried after 1, 2, 5, 10 and then every 15 minutes. After a successful automatic pickup, the earlier `*-media-backup-AD.zip` copies of the older archives the active server still lists are deleted from the download directory; newer copies, copies of archives the server no longer lists (such as those from another server) and all other files are kept. Downloading the latest archive by hand also counts as a pickup. Switching to a different active server clears the last pickup time, so the first pickup from the new server is due at once; a download that was started from the old server and finishes after the switch does not set the new server's pickup time. Incomplete `.part` files left in the download directory by a crash are deleted on startup and before each pickup, except those of a transfer in progress. If the time of a pickup cannot be saved, the client retries on the same backoff. | | `CLIENT_BACKUP_RUN_TIMEOUT` | `PT6H` | How long "Run Backup Now" waits for the server to finish. Minimum `PT1M`. If a run takes longer, the dashboard shows an error, but the backup keeps running on the server. | -| `MEDIAGARRD_SERVER_IP` | (none) | A server to connect to automatically, as `` or `:`. See [network.md](./network.md). | +| `MEDIAGARRD_SERVER_IP` | (none) | A server to connect to automatically, as ``, `:` or `https://[:]`. See [network.md](./network.md). | +| `MEDIAGARRD_SERVER_CA` | (none) | A PEM file with extra certificate authorities (or a self-signed certificate) to trust for connections to the server, in addition to the system ones. The client refuses to start if the file cannot be read. See [https.md](./https.md). | +| `CLIENT_PASSWORD` | (none) | The dashboard password. When set it overrides any stored password and the set-password form is disabled. | +| `CLIENT_RESET_PASSWORD` | `false` | `true` removes the stored dashboard password on start, so the first visitor can set a new one. Remove it again afterwards: while it stays set, every restart reopens that window. | | `MEDIAGARRD_SERVER_PORT` | `38471` | The server port tried first by "Scan Local Network" and "Connect by IP". | | `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Client` | The GitHub repository checked for new releases. | | `MEDIAGARRD_GITHUB_API_URL` | `https://api.github.com` | The GitHub API used for the release check. | | `MEDIAGARRD_UPDATE_CHECK_INTERVAL` | `PT24H` | How often the release check runs. Minimum `PT1H`. | -| `CLIENT_STATE_FILE` | `/var/lib/mediagarrd/client/state.json` | Where the client keeps its selected server, known servers, and pickup interval, inside the container. | -| `CLIENT_DOWNLOAD_DIRECTORY` | `/var/lib/mediagarrd/downloads` | Where downloaded archives are saved, inside the container. | +| `CLIENT_STATE_FILE` | `/var/lib/mediagarrd/client/state.json` | Where the client keeps its selected server, known servers, pickup interval, the time of the last pickup and the tokens of its paired servers, inside the container. The file is readable by its owner only. The dashboard password hash is stored next to it as `password.json`. | +| `CLIENT_DOWNLOAD_DIRECTORY` | `/var/lib/mediagarrd/downloads` | Where downloaded archives are saved, inside the container. Archives are written with owner-only permissions (`0600`) and directories the client creates are `0700`; an existing directory is left as it is. | + +The container starts as root only to hand the two data folders and the client's own files in them to UID 1000, then runs the client as that user. Set `PUID` and `PGID` in `environment` to use another owner, for example your own user on the host (`id -u`, `id -g`). Only the folders themselves and the client's own files are changed: the state file and its copies, `password.json`, and `*-media-backup.zip`, `*-media-backup-AD.zip` and their `.part` files. Other files in those folders, and the subfolders, are not touched. With `PUID=0` the client keeps running as root. If you set `user:` in Compose, nothing is changed and the folders must already belong to that user. + +Because Java no longer runs as root, two settings need care. With `network_mode: host` keep `CLIENT_PORT` at 1024 or above, since a non-root process cannot bind a lower port. With `cap_drop: ALL` add back `CHOWN`, `SETUID` and `SETGID` (the entrypoint needs them to hand over the folders and drop to UID 1000), or run with `user:` instead. If the state file exists but this user cannot read it, the client refuses to start and names the file and the UID, instead of moving it aside; fix its owner or permissions. To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: - `./data/client/downloads`: downloaded archives. - `./data/client/state`: the client's state. Keep it on persistent storage. + +## Failure webhook +The dashboard's Server Configuration view has a Failure Notifications panel for the connected server's optional failure webhook: a URL the server posts to when a backup fails or only partly succeeds (see the server's settings page for the message formats). Enter a URL and press Save Webhook, press Clear to turn it off, or Send Test to have the server post a test message now (if a URL is typed in the field it is saved first). The panel shows `Configured: https://host` and never the saved URL, because Discord and Slack webhook URLs are secrets; to change it, type the new one. Send Test is limited to one every 10 seconds. The URL is stored on the server, not in the client's state file. + +## Dashboard login +Opening the dashboard asks for a password. If none is set yet, whoever opens it first chooses one (at least 8 characters). Set `CLIENT_PASSWORD` to choose it yourself instead. The password is stored as a salted PBKDF2-HMAC-SHA256 hash in `password.json` next to the state file; keep that directory on persistent storage and private. +- Sessions end after 12 hours without activity or 7 days in total, and when the client restarts. +- Only one login attempt per address is checked at a time and only a few are checked at once overall; extra attempts get 429. +- Password checks from all addresses together share a budget of 30 a minute. A successful login gives its check back. When the budget is used up, logins get 429 with a `Retry-After` of a few seconds and no password is checked, and nobody is locked out for a fixed time. Someone who sends requests from many addresses can still use up the budget and make the owner wait for the next free check; set `CLIENT_PASSWORD` to a long random value and keep the dashboard behind a VPN or reverse proxy that limits access. +- After the 4th failed login from one address, further attempts from it are refused with a delay that grows from 5 seconds to 5 minutes. Behind a reverse proxy every visitor shares the proxy's address, so the delay applies to all of them. +- Forgot the password? Start once with `CLIENT_RESET_PASSWORD=true`, open the dashboard, set a new one, then remove the variable. + +## Pairing +A client must be paired with each server it uses. Choose the server in the dashboard and enter the `Pairing PIN` that the server's setup page shows after Finish Setup (it is also in the server's logs), or a pairing code from a client that is already paired. The client stores the token as soon as the server issues it and then confirms the pairing with one request. It discards the token only when the server refuses the confirmation, so after that error you can enter the same PIN or code again. If the confirmation cannot be completed (the server is unreachable or answers with an error), the client keeps the token and says so: the server confirms it on the client's next connection, which happens within seconds. If the server never received a request with it, the unconfirmed pairing expires after 5 minutes, the client then asks you to pair again, and the same PIN (or a new pairing code) works. A client that is already paired with a working token refuses to pair again (`409`); unpair it first. The token is kept in the state file per server address and is never shown. Tokens are tied to the exact address: `http://:38471` and `https://garrd.example.com` need separate pairings. diff --git a/docs/testing.md b/docs/testing.md index 3b33b9a..adefa5e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -3,17 +3,18 @@ `make test` runs both the Java tests and the browser tests. ## Browser tests -The browser tests cover the pure modules in `src/main/resources/static/js`: -- `dashboard-model.js`: how events change the dashboard state, and when the archive list reloads. -- `view-model.js`: how the connection state, known servers, and versions are rendered. -- `reachability.js`: when the client counts as unreachable. +The browser tests in `src/test/js` cover the pure modules in `src/main/resources/static/js` (dashboard state, view and message logic, formatting, API error handling, the event stream, busy handling, notifications, the webhook form, and login and pairing logic). Some also read the HTML, CSS or Java sources to check what they contain, such as the webhook panel's markup and styles and that the event names match the server's. The files in `src/test/js` are the list of what is covered. They need Node 20.19 or newer and have no dependencies. Run them on their own from the repository root: ```bash node --test src/test/js/*.test.mjs ``` +## Manual UI check +The page wiring (`auth.js`, `pairing.js`, `main.js`, the HTML and CSS) is not covered by automated tests; only the pure modules are. After changing the page, open the dashboard in a browser and check: setting the first password, logging in and out, pairing with a PIN, creating a pairing code, unpairing, and that a revoked token shows the pairing form again. + ## Java tests ```bash ./gradlew test ``` +The HTTPS tests generate a self-signed certificate with the JDK's `keytool`, so the JDK's `bin` directory must be present. diff --git a/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java index 5db0cd5..36304ee 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrd.java @@ -7,7 +7,7 @@ @SpringBootApplication @EnableScheduling -@EnableConfigurationProperties(Configuration.class) +@EnableConfigurationProperties(MediaGarrdProperties.class) public class MediaGarrd { public static void main(String[] args) { diff --git a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java similarity index 79% rename from src/main/java/wellatleastitried/mediagarrdclient/Configuration.java rename to src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java index 29bba9a..fb983fc 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/Configuration.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/MediaGarrdProperties.java @@ -5,7 +5,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mediagarrd.client") -public class Configuration { +public class MediaGarrdProperties { private String stateFile = "/var/lib/mediagarrd/client/state.json"; private String downloadDirectory = "/var/lib/mediagarrd/downloads"; @@ -16,6 +16,9 @@ public class Configuration { private String githubApiBaseUrl = "https://api.github.com"; private Duration updateCheckInterval = Duration.ofHours(24); private Duration backupRunTimeout = Duration.ofHours(6); + private String serverCa = ""; + private String password = ""; + private boolean resetPassword; public String getStateFile() { return stateFile; @@ -88,4 +91,28 @@ public Duration getBackupRunTimeout() { public void setBackupRunTimeout(Duration backupRunTimeout) { this.backupRunTimeout = backupRunTimeout; } + + public String getServerCa() { + return serverCa; + } + + public void setServerCa(String serverCa) { + this.serverCa = serverCa; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isResetPassword() { + return resetPassword; + } + + public void setResetPassword(boolean resetPassword) { + this.resetPassword = resetPassword; + } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java index 4108c86..dc815e7 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandler.java @@ -5,18 +5,28 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.ErrorResponse; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientResponseException; -import org.springframework.web.server.ResponseStatusException; +import jakarta.servlet.ServletException; + +import wellatleastitried.mediagarrdclient.service.BackupRunFailedException; import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; +import wellatleastitried.mediagarrdclient.service.ConflictException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; import wellatleastitried.mediagarrdclient.service.RequestTimeouts; +import wellatleastitried.mediagarrdclient.service.ServerRedirectException; +import wellatleastitried.mediagarrdclient.service.UpstreamResponseException; @RestControllerAdvice public class ApiExceptionHandler { @@ -28,17 +38,50 @@ record ServerError(String error) { @ExceptionHandler(RestClientResponseException.class) public ResponseEntity> serverRejected(RestClientResponseException e) { + int status = e.getStatusCode().value(); String message = null; - try { - ServerError body = e.getResponseBodyAs(ServerError.class); - message = body == null ? null : body.error(); - } catch (RuntimeException ignored) { + if (!e.getStatusCode().is5xxServerError()) { + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + message = body == null ? null : body.error(); + } catch (RuntimeException ignored) { + } } - String reason = message == null ? "MediaGarrd server responded with " + e.getStatusCode().value() : message; + String reason = message == null ? "MediaGarrd server responded with " + status : message; LOGGER.warn("MediaGarrd server rejected request: {}", reason); + if (status == HttpStatus.TOO_MANY_REQUESTS.value()) { + String retryAfter = e.getResponseHeaders() == null ? null : e.getResponseHeaders().getFirst(HttpHeaders.RETRY_AFTER); + if (retryAfter != null && retryAfter.matches("\\d{1,6}")) { + return ResponseEntity.status(e.getStatusCode()).header(HttpHeaders.RETRY_AFTER, retryAfter).body(Map.of("error", reason)); + } + } return error(e.getStatusCode(), reason); } + @ExceptionHandler(PairingRequiredException.class) + public ResponseEntity> pairingRequired(PairingRequiredException e) { + LOGGER.warn("Pairing required: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(Map.of("error", e.getMessage(), "pairing", "required")); + } + + @ExceptionHandler(ServerRedirectException.class) + public ResponseEntity> serverRedirected(ServerRedirectException e) { + LOGGER.warn("MediaGarrd server redirected the request: {}", e.getMessage()); + return error(HttpStatus.BAD_GATEWAY, e.getMessage()); + } + + @ExceptionHandler(UpstreamResponseException.class) + public ResponseEntity> upstreamInvalid(UpstreamResponseException e) { + LOGGER.warn("MediaGarrd server sent an unusable response: {}", e.getMessage()); + return error(HttpStatus.BAD_GATEWAY, e.getMessage()); + } + + @ExceptionHandler(BackupRunFailedException.class) + public ResponseEntity> backupRunFailed(BackupRunFailedException e) { + LOGGER.warn("Backup run failed on the server: {}", e.getMessage()); + return error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + } + @ExceptionHandler(BackupRunTimeoutException.class) public ResponseEntity> backupRunTimedOut(BackupRunTimeoutException e) { LOGGER.warn("Backup run timed out: {}", e.getMessage()); @@ -55,27 +98,51 @@ public ResponseEntity> serverUnreachable(ResourceAccessExcep return error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); } - @ExceptionHandler(ResponseStatusException.class) - public ResponseEntity> rejected(ResponseStatusException e) { - LOGGER.warn("Rejected request: {}", e.getReason()); - return error(e.getStatusCode(), e.getReason()); + @ExceptionHandler(InvalidRequestException.class) + public ResponseEntity> invalid(InvalidRequestException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.BAD_REQUEST, e.getMessage()); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity> notFound(NotFoundException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.NOT_FOUND, e.getMessage()); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity> conflict(ConflictException e) { + LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(HttpStatus.CONFLICT, e.getMessage()); } @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity> unreadable(HttpMessageNotReadableException e) { + if (tooLarge(e)) { + LOGGER.warn("Request body too large"); + return error(HttpStatus.CONTENT_TOO_LARGE, "Request body is too large"); + } LOGGER.warn("Unreadable request body: {}", e.getMessage()); return error(HttpStatus.BAD_REQUEST, "Request body is missing or malformed"); } - @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) - public ResponseEntity> failed(RuntimeException e) { - HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST : HttpStatus.INTERNAL_SERVER_ERROR; - if (status.is5xxServerError()) { - LOGGER.error("Request failed: {}", e.getMessage()); - } else { + @ExceptionHandler({RuntimeException.class, ServletException.class}) + public ResponseEntity> failed(Exception e) { + if (e instanceof ErrorResponse response && response.getStatusCode().is4xxClientError()) { LOGGER.warn("Rejected request: {}", e.getMessage()); + return error(response.getStatusCode(), response.getBody().getDetail()); + } + LOGGER.error("Request failed", e); + return error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal error"); + } + + private static boolean tooLarge(Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof RequestTooLargeException) { + return true; + } } - return error(status, e.getMessage()); + return false; } private static ResponseEntity> error(HttpStatusCode status, String message) { diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java new file mode 100644 index 0000000..255e3b6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/AuthController.java @@ -0,0 +1,144 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.Semaphore; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.servlet.http.HttpServletRequest; +import wellatleastitried.mediagarrdclient.dto.AuthStatusDto; +import wellatleastitried.mediagarrdclient.dto.PasswordRequest; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class); + + private static final int HASH_SLOTS = 3; + + private final Semaphore hashSlots = new Semaphore(HASH_SLOTS); + private final PasswordService passwords; + private final SessionService sessions; + private final LoginAttempts attempts; + + public AuthController(PasswordService passwords, SessionService sessions, LoginAttempts attempts) { + this.passwords = passwords; + this.sessions = sessions; + this.attempts = attempts; + } + + @PublicEndpoint + @GetMapping("/status") + public AuthStatusDto status(HttpServletRequest request) { + return new AuthStatusDto(passwords.isConfigured(), passwords.isFromEnvironment(), sessions.validate(SessionGate.sessionToken(request))); + } + + @PublicEndpoint + @PostMapping("/login") + public ResponseEntity login(@RequestBody PasswordRequest body, HttpServletRequest request) { + if (!passwords.isConfigured()) { + return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "No password is set yet")); + } + String source = request.getRemoteAddr(); + var locked = attempts.tryBegin(source); + if (locked.isPresent()) { + return tooMany(source, locked.get()); + } + if (!hashSlots.tryAcquire()) { + attempts.abandon(source); + return tooMany(source, LoginAttempts.BUSY_RETRY); + } + boolean recorded = false; + try { + boolean matched; + try { + matched = passwords.matches(body.password()); + } finally { + hashSlots.release(); + } + if (!matched) { + attempts.failed(source); + recorded = true; + LOGGER.warn("Failed dashboard login from {}", source); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "Incorrect password")); + } + attempts.succeeded(source); + recorded = true; + return signedIn(request); + } finally { + if (!recorded) { + attempts.abandon(source); + } + } + } + + private static ResponseEntity tooMany(String source, Duration wait) { + long seconds = Math.max(1, wait.plusMillis(999).toSeconds()); + LOGGER.warn("Login from {} refused, try again in {} second(s)", source, seconds); + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .header(HttpHeaders.RETRY_AFTER, Long.toString(seconds)) + .body(Map.of("error", "Too many login attempts, try again in " + seconds + " seconds")); + } + + @PublicEndpoint + @PostMapping("/set-password") + public ResponseEntity setPassword(@RequestBody PasswordRequest body, HttpServletRequest request) { + passwords.setInitial(body.password()); + sessions.clear(); + LOGGER.info("Dashboard password set from {}", request.getRemoteAddr()); + return signedIn(request); + } + + @PublicEndpoint + @PostMapping("/logout") + public ResponseEntity logout(HttpServletRequest request) { + sessions.invalidate(SessionGate.sessionToken(request)); + return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, cookie("", Duration.ZERO, request).toString()).build(); + } + + private ResponseEntity signedIn(HttpServletRequest request) { + String token = sessions.create(); + return ResponseEntity.ok() + .header(HttpHeaders.SET_COOKIE, cookie(token, null, request).toString()) + .body(Map.of("authenticated", true)); + } + + private static ResponseCookie cookie(String value, Duration maxAge, HttpServletRequest request) { + ResponseCookie.ResponseCookieBuilder builder = ResponseCookie.from(SessionGate.COOKIE, value) + .httpOnly(true) + .secure(isSecure(request)) + .sameSite("Strict") + .path("/"); + if (maxAge != null) { + builder.maxAge(maxAge); + } + return builder.build(); + } + + static boolean isSecure(HttpServletRequest request) { + if (request.isSecure()) { + return true; + } + String forwarded = request.getHeader("X-Forwarded-Proto"); + if (forwarded == null) { + return false; + } + int comma = forwarded.indexOf(','); + return "https".equalsIgnoreCase((comma < 0 ? forwarded : forwarded.substring(0, comma)).trim()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java b/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java new file mode 100644 index 0000000..8d59635 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/BodyLimitFilter.java @@ -0,0 +1,129 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class BodyLimitFilter extends OncePerRequestFilter { + + static final long MAX_BODY_BYTES = 64 * 1024; + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return !request.getRequestURI().startsWith("/api/"); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + if (request.getContentLengthLong() > MAX_BODY_BYTES) { + response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.getWriter().write("{\"error\":\"Request body is too large\"}"); + return; + } + chain.doFilter(new LimitedRequest(request, MAX_BODY_BYTES), response); + } + + private static final class LimitedRequest extends HttpServletRequestWrapper { + + private final long limit; + private ServletInputStream stream; + + private LimitedRequest(HttpServletRequest request, long limit) { + super(request); + this.limit = limit; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + if (stream == null) { + stream = new LimitedStream(super.getInputStream(), limit); + } + return stream; + } + + @Override + public BufferedReader getReader() throws IOException { + String encoding = getCharacterEncoding(); + Charset charset = encoding == null ? StandardCharsets.UTF_8 : Charset.forName(encoding); + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } + } + + private static final class LimitedStream extends ServletInputStream { + + private final ServletInputStream delegate; + private final long limit; + private long count; + + private LimitedStream(ServletInputStream delegate, long limit) { + this.delegate = delegate; + this.limit = limit; + } + + @Override + public int read() throws IOException { + int value = delegate.read(); + if (value >= 0) { + counted(1); + } + return value; + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + int read = delegate.read(buffer, offset, length); + if (read > 0) { + counted(read); + } + return read; + } + + private void counted(int bytes) throws IOException { + count += bytes; + if (count > limit) { + throw new RequestTooLargeException(limit); + } + } + + @Override + public boolean isFinished() { + return delegate.isFinished(); + } + + @Override + public boolean isReady() { + return delegate.isReady(); + } + + @Override + public void setReadListener(ReadListener listener) { + delegate.setReadListener(listener); + } + + @Override + public void close() throws IOException { + delegate.close(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java index f1ea456..f6ca375 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -1,6 +1,5 @@ package wellatleastitried.mediagarrdclient.api; -import java.net.URI; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; @@ -23,6 +22,7 @@ import wellatleastitried.mediagarrdclient.service.DashboardService; import wellatleastitried.mediagarrdclient.service.ServerApiService; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; @RestController @RequestMapping("/api/client") @@ -33,19 +33,22 @@ public class ClientController { private final ServerApiService serverApiService; private final BackupPickupService pickupService; private final DashboardService dashboardService; + private final ServerSelectionService selectionService; public ClientController( ClientStateService stateService, ServerDiscoveryService discoveryService, ServerApiService serverApiService, BackupPickupService pickupService, - DashboardService dashboardService + DashboardService dashboardService, + ServerSelectionService selectionService ) { this.stateService = stateService; this.discoveryService = discoveryService; this.serverApiService = serverApiService; this.pickupService = pickupService; this.dashboardService = dashboardService; + this.selectionService = selectionService; } @GetMapping("/status") @@ -67,20 +70,7 @@ public List discover() { @PutMapping("/server") public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { - if (!isBlank(request.serverUrl())) { - stateService.setActiveServer(normalizeServerUrl(request.serverUrl())); - return currentStatus(); - } - if (isBlank(request.serverIp())) { - throw new IllegalArgumentException("Either serverUrl or serverIp must be provided"); - } - Integer port = request.serverPort(); - if (port != null && (port < 1 || port > 65535)) { - throw new IllegalArgumentException("serverPort must be between 1 and 65535"); - } - String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) - .orElseThrow(() -> new IllegalArgumentException("No MediaGarrd server found at " + request.serverIp().trim())); - stateService.setActiveServer(resolved); + selectionService.select(request); return currentStatus(); } @@ -118,20 +108,4 @@ public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest r private ClientStatusDto currentStatus() { return new ClientStatusDto(stateService.getActiveServer(), stateService.getPickupInterval(), stateService.getKnownServers()); } - - static String normalizeServerUrl(String serverUrl) { - String trimmed = serverUrl.trim().replaceAll("/+$", ""); - try { - URI uri = URI.create(trimmed); - if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && !isBlank(uri.getHost())) { - return trimmed; - } - } catch (IllegalArgumentException ignored) { - } - throw new IllegalArgumentException("serverUrl must be an http:// or https:// URL: " + serverUrl); - } - - private static boolean isBlank(String value) { - return value == null || value.isBlank(); - } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java similarity index 77% rename from src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java rename to src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java index 15d38e1..dcc4ad3 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcaster.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcaster.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrdclient.service; +package wellatleastitried.mediagarrdclient.api; import java.io.IOException; import java.time.Duration; @@ -12,6 +12,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.LongFunction; +import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,11 +20,13 @@ import org.springframework.stereotype.Service; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; - import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.service.ClientEvent; +import wellatleastitried.mediagarrdclient.service.ClientEventPublisher; +import wellatleastitried.mediagarrdclient.service.SessionService; @Service -public class ClientEventBroadcaster { +public class ClientEventBroadcaster implements ClientEventPublisher { private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventBroadcaster.class); private static final Duration PING_INTERVAL = Duration.ofSeconds(20); @@ -40,11 +43,13 @@ public class ClientEventBroadcaster { private final class Subscriber { private final SseEmitter emitter; + private final String sessionKey; private final BlockingQueue queue = new LinkedBlockingQueue<>(queueCapacity); private volatile boolean closed; - private Subscriber(SseEmitter emitter) { + private Subscriber(SseEmitter emitter, String sessionKey) { this.emitter = emitter; + this.sessionKey = sessionKey; } private boolean offer(ClientEvent message) { @@ -70,7 +75,7 @@ private void run() { if (closed || polled == CLOSE) { break; } - if (polled == null && System.nanoTime() >= deadline) { + if (polled == null && (System.nanoTime() >= deadline || sessionKey != null && !sessionActive.test(sessionKey))) { break; } ClientEvent message = polled == null ? PING : polled; @@ -106,13 +111,15 @@ private void run() { private final long emitterTimeoutMillis; private final ThreadFactory threadFactory; private final LongFunction emitterFactory; + private final Predicate sessionActive; 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); + public ClientEventBroadcaster(SessionService sessions) { + this(PING_INTERVAL, MAX_SUBSCRIBERS, QUEUE_CAPACITY, STREAM_LIFETIME, EMITTER_TIMEOUT, writerThreads(), SseEmitter::new, sessions::isActive); + sessions.addEndedListener(this::endSession); } ClientEventBroadcaster( @@ -124,6 +131,20 @@ public ClientEventBroadcaster() { ThreadFactory threadFactory, LongFunction emitterFactory ) { + this(pingInterval, maxSubscribers, queueCapacity, streamLifetime, emitterTimeout, threadFactory, emitterFactory, key -> true); + } + + ClientEventBroadcaster( + Duration pingInterval, + int maxSubscribers, + int queueCapacity, + Duration streamLifetime, + Duration emitterTimeout, + ThreadFactory threadFactory, + LongFunction emitterFactory, + Predicate sessionActive + ) { + this.sessionActive = sessionActive; this.pingInterval = pingInterval; this.maxSubscribers = maxSubscribers; this.queueCapacity = queueCapacity; @@ -139,8 +160,12 @@ private static ThreadFactory writerThreads() { } public Optional subscribe(List initial) { + return subscribe(null, initial); + } + + public Optional subscribe(String sessionKey, List initial) { SseEmitter emitter = emitterFactory.apply(emitterTimeoutMillis); - Subscriber subscriber = new Subscriber(emitter); + Subscriber subscriber = new Subscriber(emitter, sessionKey); Thread writer = threadFactory.newThread(subscriber::run); synchronized (lock) { if (shutdown || subscribers.size() >= maxSubscribers) { @@ -156,12 +181,25 @@ public Optional subscribe(List initial) { return Optional.of(emitter); } + @Override public void publish(String name, String data) { synchronized (lock) { broadcast(new ClientEvent(name, data)); } } + void endSession(String sessionKey) { + synchronized (lock) { + subscribers.removeIf(subscriber -> { + boolean ends = sessionKey.equals(subscriber.sessionKey); + if (ends) { + subscriber.close(); + } + return ends; + }); + } + } + public int subscriberCount() { synchronized (lock) { return subscribers.size(); diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java index cb8d71f..1f2890d 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientEventsController.java @@ -4,7 +4,6 @@ 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; @@ -15,7 +14,9 @@ import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; +import jakarta.servlet.http.HttpServletRequest; import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.SessionService; @RestController @RequestMapping("/api/client") @@ -24,16 +25,18 @@ public class ClientEventsController { private static final Logger LOGGER = LoggerFactory.getLogger(ClientEventsController.class); private final DashboardService dashboard; + private final ClientEventBroadcaster broadcaster; - public ClientEventsController(DashboardService dashboard) { + public ClientEventsController(DashboardService dashboard, ClientEventBroadcaster broadcaster) { this.dashboard = dashboard; + this.broadcaster = broadcaster; } @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public ResponseEntity events() { - return dashboard.subscribe() + public ResponseEntity events(HttpServletRequest request) { + String sessionKey = SessionService.keyOf(SessionGate.sessionToken(request)); + return dashboard.subscribe(initial -> broadcaster.subscribe(sessionKey, initial)) .map(emitter -> ResponseEntity.ok() - .cacheControl(CacheControl.noCache()) .header("X-Accel-Buffering", "no") .body(emitter)) .orElseGet(() -> ResponseEntity.status(503).build()); diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java b/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java new file mode 100644 index 0000000..8615e66 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/CsrfCheck.java @@ -0,0 +1,53 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.net.URI; +import java.util.Locale; +import java.util.Set; + +import jakarta.servlet.http.HttpServletRequest; + +final class CsrfCheck { + + static final String HEADER = "X-MediaGarrd-Request"; + private static final Set SAFE_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE"); + + private CsrfCheck() { + } + + static boolean allows(HttpServletRequest request) { + if (SAFE_METHODS.contains(request.getMethod().toUpperCase(Locale.ROOT))) { + return true; + } + String fetchSite = request.getHeader("Sec-Fetch-Site"); + if (fetchSite != null) { + return "same-origin".equalsIgnoreCase(fetchSite.trim()); + } + String origin = request.getHeader("Origin"); + if (origin == null) { + return "1".equals(request.getHeader(HEADER)); + } + String authority = originAuthority(origin); + if (authority == null) { + return false; + } + return authority.equalsIgnoreCase(firstValue(request.getHeader("Host"))) + || authority.equalsIgnoreCase(firstValue(request.getHeader("X-Forwarded-Host"))); + } + + private static String originAuthority(String origin) { + try { + URI uri = URI.create(origin.trim()); + return uri.getScheme() == null ? null : uri.getRawAuthority(); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static String firstValue(String header) { + if (header == null) { + return null; + } + int comma = header.indexOf(','); + return (comma < 0 ? header : header.substring(0, comma)).trim(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java new file mode 100644 index 0000000..666b104 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/PairingController.java @@ -0,0 +1,39 @@ +package wellatleastitried.mediagarrdclient.api; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.PairRequest; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; + +@RestController +@RequestMapping("/api/client/pairing") +public class PairingController { + + private final ClientPairingService pairing; + + public PairingController(ClientPairingService pairing) { + this.pairing = pairing; + } + + @PostMapping + public PairingResultDto pair(@RequestBody PairRequest request) { + return pairing.pair(request.pin(), request.name()); + } + + @PostMapping("/code") + public PairingCodeDto createCode() { + return pairing.createCode(); + } + + @DeleteMapping + public UnpairResultDto unpair() { + return pairing.unpair(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java b/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java new file mode 100644 index 0000000..f274d2f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/PublicEndpoint.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface PublicEndpoint { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java b/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java new file mode 100644 index 0000000..909b0ee --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/RequestTooLargeException.java @@ -0,0 +1,10 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +public class RequestTooLargeException extends IOException { + + public RequestTooLargeException(long limit) { + super("The request body is larger than " + limit + " bytes"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java b/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java new file mode 100644 index 0000000..89017bd --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/SecurityHeadersFilter.java @@ -0,0 +1,33 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SecurityHeadersFilter extends OncePerRequestFilter { + + static final String CONTENT_SECURITY_POLICY = "default-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'"; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + response.setHeader("X-Frame-Options", "DENY"); + response.setHeader("Content-Security-Policy", CONTENT_SECURITY_POLICY); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.setHeader("Referrer-Policy", "no-referrer"); + if (request.getRequestURI().startsWith("/api/")) { + response.setHeader("Cache-Control", "no-store"); + } + chain.doFilter(request, response); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java index 642ca4d..7fd7361 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java @@ -1,5 +1,6 @@ package wellatleastitried.mediagarrdclient.api; +import java.time.Duration; import java.util.List; import org.slf4j.Logger; @@ -19,7 +20,9 @@ import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; import wellatleastitried.mediagarrdclient.dto.ServiceDto; import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServiceNames; @RestController @RequestMapping("/api/client") @@ -27,6 +30,10 @@ public class ServerConfigController { private static final Logger LOGGER = LoggerFactory.getLogger(ServerConfigController.class); + private static final Duration MIN_INTERVAL = Duration.ofMinutes(15); + private static final Duration MAX_INTERVAL = Duration.ofDays(365); + static final String INTERVAL_MESSAGE = "Backup interval must be between 15 minutes and 365 days"; + private final ClientStateService stateService; private final ServerApiService serverApiService; @@ -38,13 +45,14 @@ public ServerConfigController(ClientStateService stateService, ServerApiService @GetMapping("/server-config") public ServerConfigDto serverConfig() { String activeServer = stateService.requireActiveServer(); - LOGGER.info("GET /api/client/server-config, forwarding to {}", activeServer); + LOGGER.debug("GET /api/client/server-config, forwarding to {}", activeServer); return serverApiService.serverConfig(activeServer); } @PutMapping("/server-config") public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) { String activeServer = stateService.requireActiveServer(); + requireValidInterval(request.backupInterval()); LOGGER.info("PUT /api/client/server-config, request={}, target={}", request, activeServer); ServerConfigDto config = serverApiService.updateServerConfig(activeServer, request.backupLocation(), request.retentionCount()); if (request.backupInterval() == null) { @@ -54,10 +62,16 @@ public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) return new ServerConfigDto(config.backupLocation(), config.retentionCount(), status.backupInterval()); } + private static void requireValidInterval(Duration interval) { + if (interval != null && (interval.compareTo(MIN_INTERVAL) < 0 || interval.compareTo(MAX_INTERVAL) > 0)) { + throw new InvalidRequestException(INTERVAL_MESSAGE); + } + } + @GetMapping("/services") public List services() { String activeServer = stateService.requireActiveServer(); - LOGGER.info("GET /api/client/services, forwarding to {}", activeServer); + LOGGER.debug("GET /api/client/services, forwarding to {}", activeServer); return serverApiService.listServices(activeServer); } @@ -71,6 +85,7 @@ public ServiceDto addService(@RequestBody ServiceDto service) { @PutMapping("/services/{name}") public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceDto service) { + ServiceNames.require(name); String activeServer = stateService.requireActiveServer(); LOGGER.info("PUT /api/client/services/{}, name={}, target={}", name, service.name(), activeServer); return serverApiService.updateService(activeServer, name, service); @@ -79,6 +94,7 @@ public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceD @DeleteMapping("/services/{name}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeService(@PathVariable String name) { + ServiceNames.require(name); String activeServer = stateService.requireActiveServer(); LOGGER.info("DELETE /api/client/services/{}, target={}", name, activeServer); serverApiService.removeService(activeServer, name); diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java b/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java new file mode 100644 index 0000000..ad4575b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/SessionGate.java @@ -0,0 +1,71 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.io.IOException; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.mvc.ParameterizableViewController; +import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; +import org.springframework.web.util.WebUtils; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@Component +public class SessionGate implements HandlerInterceptor { + + static final String COOKIE = "mg_session"; + + private final SessionService sessions; + + public SessionGate(SessionService sessions) { + this.sessions = sessions; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + if (request.getDispatcherType() != DispatcherType.REQUEST) { + return true; + } + if (!CsrfCheck.allows(request)) { + return reject(response, HttpServletResponse.SC_FORBIDDEN, "{\"error\":\"Cross-site request rejected\"}"); + } + if (isStaticContent(handler) || isPublic(handler)) { + return true; + } + if (sessions.validate(sessionToken(request))) { + return true; + } + return reject(response, HttpServletResponse.SC_UNAUTHORIZED, "{\"error\":\"Login required\",\"login\":\"required\"}"); + } + + static String sessionToken(HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, COOKIE); + return cookie == null ? null : cookie.getValue(); + } + + private static boolean isStaticContent(Object handler) { + return handler instanceof ResourceHttpRequestHandler || isWelcomePage(handler); + } + + private static boolean isWelcomePage(Object handler) { + return handler instanceof ParameterizableViewController view && "forward:index.html".equals(view.getViewName()); + } + + private static boolean isPublic(Object handler) { + return handler instanceof HandlerMethod method && method.hasMethodAnnotation(PublicEndpoint.class); + } + + private static boolean reject(HttpServletResponse response, int status, String body) throws IOException { + response.setStatus(status); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.getWriter().write(body); + return false; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java b/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java new file mode 100644 index 0000000..9edd4be --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/WebMvcConfig.java @@ -0,0 +1,20 @@ +package wellatleastitried.mediagarrdclient.api; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + private final SessionGate sessionGate; + + public WebMvcConfig(SessionGate sessionGate) { + this.sessionGate = sessionGate; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(sessionGate).addPathPatterns("/**"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java new file mode 100644 index 0000000..270976a --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/WebhookController.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.dto.WebhookUpdateRequest; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@RestController +@RequestMapping("/api/client/notifications/webhook") +public class WebhookController { + + private static final Logger LOGGER = LoggerFactory.getLogger(WebhookController.class); + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + + public WebhookController(ClientStateService stateService, ServerApiService serverApiService) { + this.stateService = stateService; + this.serverApiService = serverApiService; + } + + @GetMapping + public WebhookStatusDto webhook() { + String activeServer = stateService.requireActiveServer(); + LOGGER.debug("GET /api/client/notifications/webhook, forwarding to {}", activeServer); + return serverApiService.webhook(activeServer); + } + + @PutMapping + public WebhookStatusDto updateWebhook(@RequestBody WebhookUpdateRequest request) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/notifications/webhook, target={}", activeServer); + return serverApiService.updateWebhook(activeServer, request.url()); + } + + @PostMapping("/test") + public WebhookTestDto testWebhook() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("POST /api/client/notifications/webhook/test, target={}", activeServer); + return serverApiService.testWebhook(activeServer); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java new file mode 100644 index 0000000..784dadb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/AuthStatusDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record AuthStatusDto(boolean passwordSet, boolean passwordFromEnvironment, boolean authenticated) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java index b961cec..7018c9e 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/DashboardState.java @@ -8,6 +8,7 @@ public record DashboardState( LinkState link, Boolean running, HealthSummary health, - VersionsDto versions + VersionsDto versions, + PairingState pairing ) { } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java new file mode 100644 index 0000000..c45c6bf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PairRequest(String pin, String name) { + + @Override + public String toString() { + return "PairRequest[name=" + name + "]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java new file mode 100644 index 0000000..8633ebf --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingCodeDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Instant; + +public record PairingCodeDto(String code, Instant expiresAt) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java new file mode 100644 index 0000000..870c922 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingResultDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PairingResultDto(boolean paired, String name, String note) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java new file mode 100644 index 0000000..3ca4624 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PairingState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.dto; + +public enum PairingState { + NONE, + PAIRED, + REQUIRED, + REJECTED +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java new file mode 100644 index 0000000..6791500 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/PasswordRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record PasswordRequest(String password) { + + @Override + public String toString() { + return "PasswordRequest[]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java new file mode 100644 index 0000000..bc1d2da --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/UnpairResultDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record UnpairResultDto(boolean serverRevoked, String warning) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java new file mode 100644 index 0000000..65967bc --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookStatusDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookStatusDto(boolean configured, String target) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java new file mode 100644 index 0000000..33c6519 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookTestDto.java @@ -0,0 +1,4 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookTestDto(boolean delivered, Integer status, String error) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java new file mode 100644 index 0000000..7bf8855 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/WebhookUpdateRequest.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.dto; + +public record WebhookUpdateRequest(String url) { + + @Override + public String toString() { + return "WebhookUpdateRequest[url=]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java similarity index 58% rename from src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java rename to src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java index 798318a..f59adf9 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/protocol/Endpoints.java @@ -1,4 +1,4 @@ -package wellatleastitried.mediagarrdclient.api; +package wellatleastitried.mediagarrdclient.protocol; public enum Endpoints { @@ -9,7 +9,12 @@ public enum Endpoints { SERVER_SCHEDULE("/api/v1/schedule"), SERVER_CONFIG("/api/v1/config"), SERVER_SERVICES("/api/v1/services"), - SERVER_EVENTS("/api/v1/events"); + SERVER_WEBHOOK("/api/v1/notifications/webhook"), + SERVER_WEBHOOK_TEST("/api/v1/notifications/webhook/test"), + SERVER_EVENTS("/api/v1/events"), + SERVER_PAIR("/api/v1/pair"), + SERVER_PAIRING_CODES("/api/v1/pairing-codes"), + SERVER_CLIENTS("/api/v1/clients"); private final String path; diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java index cee0e67..7b379c1 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.time.Clock; import java.time.Duration; @@ -9,21 +10,26 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientResponseException; +import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; @@ -34,13 +40,16 @@ public class BackupPickupService { private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; private static final String ZIP_SUFFIX = ".zip"; + private static final String PART_SUFFIX = ".part"; static final Duration FINISHED_TASK_RETENTION = Duration.ofMinutes(10); + static final String GENERIC_FAILURE = "The download failed, see the client log for details"; private enum PickupStatus { QUEUED, RUNNING, COMPLETED, FAILED } private final class PickupTask { private final String taskId = UUID.randomUUID().toString(); private final BackupDto backup; + private final boolean latest; private volatile PickupStatus status = PickupStatus.QUEUED; private volatile long bytesWritten; private volatile long totalBytes; @@ -48,8 +57,9 @@ private final class PickupTask { private volatile String error; private volatile Instant finishedAt; - private PickupTask(BackupDto backup) { + private PickupTask(BackupDto backup, boolean latest) { this.backup = backup; + this.latest = latest; this.totalBytes = backup.sizeBytes(); } @@ -81,70 +91,127 @@ private PickupProgressDto progress() { } } - private final Configuration configuration; + private final MediaGarrdProperties configuration; private final ClientStateService clientStateService; private final ServerApiService serverApiService; private final Clock clock; private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final ExecutorService scheduledExecutor = Executors.newVirtualThreadPerTaskExecutor(); + private final AtomicBoolean scheduledRunning = new AtomicBoolean(); + private final AtomicBoolean noBackupsReported = new AtomicBoolean(); private final Map tasks = new LinkedHashMap<>(); - private volatile Instant nextPickup; + private final PickupSchedule schedule; @Autowired - public BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService) { + public BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService) { this(configuration, clientStateService, serverApiService, Clock.systemUTC()); } - BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { + BackupPickupService(MediaGarrdProperties configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { this.configuration = configuration; this.clientStateService = clientStateService; this.serverApiService = serverApiService; this.clock = clock; - this.nextPickup = clock.instant().plus(clientStateService.getPickupInterval()); + this.schedule = new PickupSchedule(clock); + clientStateService.addActiveServerListener(server -> noBackupsReported.set(false)); + } + + @PostConstruct + void removeStalePartFilesAtStartup() { + removeStalePartFiles(downloadsDirectory()); } @Scheduled(fixedDelay = 60_000) public void scheduledPickup() { - Instant now = clock.instant(); - if (now.isBefore(nextPickup)) { + if (!paired() || !schedule.due(clientStateService.getLastPickupAt(), clientStateService.getPickupInterval()) + || !scheduledRunning.compareAndSet(false, true)) { return; } - nextPickup = now.plus(clientStateService.getPickupInterval()); try { - LOGGER.info("Scheduled pickup saved {}, next pickup at {}", pickupLatestAuto(), nextPickup); + scheduledExecutor.execute(this::runScheduledPickup); + } catch (RejectedExecutionException e) { + scheduledRunning.set(false); + } + } + + void runScheduledPickup() { + try { + Path saved = pickupLatestAuto(); + noBackupsReported.set(false); + if (saved == null) { + LOGGER.debug("Scheduled pickup deferred, the latest backup is being downloaded by a manual pickup"); + } else { + LOGGER.info("Scheduled pickup saved {}, next pickup at {}", saved, nextPickup()); + } + } catch (NoBackupsException e) { + Instant retryAt = schedule.failed(); + if (noBackupsReported.compareAndSet(false, true)) { + LOGGER.info("The server has no backups yet, checking again at {}. Further checks are logged at DEBUG until a backup exists", retryAt); + } else { + LOGGER.debug("The server still has no backups, checking again at {}", retryAt); + } } catch (RuntimeException e) { - LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", nextPickup, e.getMessage()); + noBackupsReported.set(false); + LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", schedule.failed(), e.getMessage()); + } finally { + scheduledRunning.set(false); } } public Duration updatePickupInterval(Duration interval) { Duration updated = clientStateService.setPickupInterval(interval); - nextPickup = clock.instant().plus(updated); + schedule.reset(); return updated; } + public Instant nextPickup() { + return schedule.dueAt(clientStateService.getLastPickupAt(), clientStateService.getPickupInterval()); + } + + boolean scheduledRunning() { + return scheduledRunning.get(); + } + + private boolean paired() { + String server = clientStateService.getActiveServer(); + return server != null && !server.isBlank() && clientStateService.hasPairing(server); + } + + private void pickupSucceeded(String server) { + try { + if (clientStateService.recordPickup(server, clock.instant())) { + schedule.reset(); + } + } catch (RuntimeException e) { + LOGGER.warn("Could not record the pickup time, next attempt at {}: {}", schedule.failed(), e.getMessage()); + } + } + public PickupStartDto startPickupLatestTask() { String server = clientStateService.requireActiveServer(); - return startPickupTask(server, latest(serverApiService.listBackups(server))); + return startPickupTask(server, latest(serverApiService.listBackups(server)), true); } public PickupStartDto startPickupByIdTask(String backupId) { String server = clientStateService.requireActiveServer(); - BackupDto backup = serverApiService.listBackups(server).stream() + List backups = serverApiService.listBackups(server); + BackupDto backup = backups.stream() .filter(candidate -> candidate.id().equals(backupId)) .findFirst() - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup not found: " + backupId)); - return startPickupTask(server, backup); + .orElseThrow(() -> new NotFoundException("Backup not found: " + backupId)); + return startPickupTask(server, backup, backup.equals(backups.getFirst())); } public synchronized PickupProgressDto pickupProgress(String taskId) { PickupTask task = tasks.get(taskId); if (task == null) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: " + taskId); + throw new NotFoundException("Pickup task not found: " + taskId); } return task.progress(); } - private synchronized PickupStartDto startPickupTask(String server, BackupDto backup) { + private synchronized PickupStartDto startPickupTask(String server, BackupDto backup, boolean latest) { + requireArchiveFileName(backup.fileName()); evictFinishedTasks(); PickupTask running = tasks.values().stream() .filter(task -> !task.finished() && task.backup.id().equals(backup.id())) @@ -155,20 +222,37 @@ private synchronized PickupStartDto startPickupTask(String server, BackupDto bac return running.started(); } - PickupTask task = new PickupTask(backup); - tasks.put(task.taskId, task); Path downloads = downloadsDirectory(); + removeStalePartFiles(downloads); + Path destination = inside(downloads, backup.fileName()); Path existing = existingCopy(downloads, backup); + PickupTask task = new PickupTask(backup, latest); + tasks.put(task.taskId, task); if (existing != null) { LOGGER.info("Backup {} is already downloaded at {}", backup.id(), existing); task.complete(existing); + if (latest) { + pickupSucceeded(server); + } } else { - executor.submit(() -> download(server, inside(downloads, backup.fileName()), task)); + try { + executor.execute(() -> download(server, destination, task)); + } catch (RejectedExecutionException e) { + task.fail(GENERIC_FAILURE); + } } return task.started(); } private void download(String server, Path destination, PickupTask task) { + try { + transfer(server, destination, task, task.latest ? () -> pickupSucceeded(server) : null); + } catch (RuntimeException e) { + LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + } + } + + private Path transfer(String server, Path destination, PickupTask task, Runnable afterSaved) { task.status = PickupStatus.RUNNING; try { Path saved = serverApiService.downloadById(server, task.backup.id(), destination, (written, total) -> { @@ -177,14 +261,31 @@ private void download(String server, Path destination, PickupTask task) { task.totalBytes = total; } }); + if (afterSaved != null) { + afterSaved.run(); + } task.complete(saved); LOGGER.info("Pickup task {} saved {}", task.taskId, saved); + return saved; } catch (RuntimeException e) { - task.fail(e.getMessage()); - LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + task.fail(userMessage(e)); + throw e; } } + private static String userMessage(RuntimeException e) { + if (e instanceof DownloadFailedException || e instanceof PairingRequiredException || e instanceof ServerRedirectException) { + return e.getMessage(); + } + if (e instanceof RestClientResponseException response) { + return "MediaGarrd server responded with " + response.getStatusCode().value(); + } + if (e instanceof ResourceAccessException) { + return "MediaGarrd server is unreachable"; + } + return GENERIC_FAILURE; + } + private void evictFinishedTasks() { Instant cutoff = clock.instant().minus(FINISHED_TASK_RETENTION); tasks.values().removeIf(task -> task.finished() && task.finishedAt.isBefore(cutoff)); @@ -194,19 +295,72 @@ private Path pickupLatestAuto() { String server = clientStateService.requireActiveServer(); List backups = serverApiService.listBackups(server); BackupDto latest = latest(backups); + requireArchiveFileName(latest.fileName()); Path downloads = downloadsDirectory(); + removeStalePartFiles(downloads); Path existing = existingCopy(downloads, latest); if (existing != null) { LOGGER.info("Scheduled pickup skipped, backup {} is already downloaded at {}", latest.id(), existing); + pickupSucceeded(server); return existing; } - Path downloaded = serverApiService.downloadById(server, latest.id(), inside(downloads, autoFileName(latest)), null); - deleteIfSameSize(inside(downloads, latest.fileName()), latest); - if (backups.size() > 1) { - deleteQuietly(inside(downloads, autoFileName(backups.get(1)))); + Path destination = inside(downloads, autoFileName(latest)); + ScheduledRegistration registration = registerScheduledTask(downloads, latest); + if (registration.existing() != null) { + pickupSucceeded(server); + return registration.existing(); + } + PickupTask task = registration.task(); + if (task == null) { + return null; + } + return transfer(server, destination, task, () -> { + removeSuperseded(downloads, backups, latest); + pickupSucceeded(server); + }); + } + + private record ScheduledRegistration(PickupTask task, Path existing) { + } + + private synchronized ScheduledRegistration registerScheduledTask(Path downloads, BackupDto latest) { + evictFinishedTasks(); + Path existing = existingCopy(downloads, latest); + if (existing != null) { + return new ScheduledRegistration(null, existing); + } + boolean running = tasks.values().stream().anyMatch(task -> !task.finished() && task.backup.id().equals(latest.id())); + if (running) { + return new ScheduledRegistration(null, null); + } + PickupTask task = new PickupTask(latest, true); + tasks.put(task.taskId, task); + return new ScheduledRegistration(task, null); + } + + private synchronized void removeStalePartFiles(Path downloads) { + if (!Files.isDirectory(downloads)) { + return; + } + Set inProgress = tasks.values().stream() + .filter(task -> !task.finished()) + .flatMap(task -> Stream.of(task.backup.fileName(), autoFileName(task.backup))) + .map(name -> name + PART_SUFFIX) + .collect(Collectors.toSet()); + try (Stream entries = Files.list(downloads)) { + entries + .filter(path -> path.getFileName().toString().endsWith(PART_SUFFIX)) + .filter(path -> !inProgress.contains(path.getFileName().toString())) + .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) + .forEach(path -> { + if (QuietFiles.delete(path)) { + LOGGER.info("Removed incomplete download {}", path.getFileName()); + } + }); + } catch (IOException e) { + LOGGER.warn("Could not look for incomplete downloads in {}: {}", downloads, e.getMessage()); } - return downloaded; } private Path existingCopy(Path downloads, BackupDto backup) { @@ -217,9 +371,29 @@ private Path existingCopy(Path downloads, BackupDto backup) { .orElse(null); } - private void deleteIfSameSize(Path path, BackupDto backup) { - if (hasSize(path, backup.sizeBytes())) { - deleteQuietly(path); + private static void removeSuperseded(Path downloads, List backups, BackupDto current) { + try { + backups.stream() + .skip(1) + .filter(backup -> !backup.id().equals(current.id())) + .map(backup -> autoFileName(backup)) + .filter(name -> name.endsWith(AUTO_DOWNLOAD_SUFFIX + ZIP_SUFFIX)) + .map(name -> downloads.resolve(name).normalize()) + .filter(path -> downloads.equals(path.getParent())) + .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) + .forEach(path -> { + if (QuietFiles.delete(path)) { + LOGGER.info("Removed superseded download {}", path.getFileName()); + } + }); + } catch (RuntimeException e) { + LOGGER.warn("Could not remove superseded downloads in {}: {}", downloads, e.getMessage()); + } + } + + private static void requireArchiveFileName(String fileName) { + if (!fileName.endsWith(ZIP_SUFFIX) || fileName.endsWith(PART_SUFFIX)) { + throw new InvalidRequestException("Backup file name must end in " + ZIP_SUFFIX + ": " + fileName); } } @@ -232,19 +406,9 @@ private static boolean hasSize(Path path, long size) { } } - private static void deleteQuietly(Path path) { - try { - if (Files.deleteIfExists(path)) { - LOGGER.info("Removed superseded download {}", path.getFileName()); - } - } catch (IOException e) { - LOGGER.warn("Could not remove {}: {}", path, e.getMessage()); - } - } - private static BackupDto latest(List backups) { if (backups.isEmpty()) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No backups found on server"); + throw new NoBackupsException(); } return backups.getFirst(); } @@ -259,7 +423,7 @@ private static String autoFileName(BackupDto backup) { private static Path inside(Path downloads, String fileName) { Path path = downloads.resolve(fileName).normalize(); if (!downloads.equals(path.getParent())) { - throw new IllegalArgumentException("Backup file name must not leave the download directory: " + fileName); + throw new InvalidRequestException("Backup file name must not leave the download directory: " + fileName); } return path; } @@ -271,5 +435,6 @@ private Path downloadsDirectory() { @PreDestroy void shutdown() { executor.shutdownNow(); + scheduledExecutor.shutdownNow(); } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java new file mode 100644 index 0000000..f79dec9 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupRunFailedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class BackupRunFailedException extends RuntimeException { + + public BackupRunFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java new file mode 100644 index 0000000..82db7a3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupWatcher.java @@ -0,0 +1,109 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.function.BooleanSupplier; +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; + +final class BackupWatcher { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupWatcher.class); + + private final ServerApiService serverApiService; + private final DashboardEvents events; + private final Clock clock; + private final Object lock; + private final Duration interval; + private final Supplier server; + private final LongSupplier epoch; + private final BooleanSupplier degraded; + private final CoalescedRefresh refresh; + private List seen; + private Instant checkedAt; + + BackupWatcher( + ServerApiService serverApiService, + DashboardEvents events, + Clock clock, + Object lock, + Executor executor, + Duration interval, + Supplier server, + LongSupplier epoch, + BooleanSupplier degraded + ) { + this.serverApiService = serverApiService; + this.events = events; + this.clock = clock; + this.lock = lock; + this.interval = interval; + this.server = server; + this.epoch = epoch; + this.degraded = degraded; + this.refresh = new CoalescedRefresh(lock, executor, this::fetch); + } + + void forget() { + seen = null; + checkedAt = null; + } + + void forgetListing() { + seen = null; + } + + void requestWhenDue() { + if (!refresh.busy() && (checkedAt == null || Duration.between(checkedAt, clock.instant()).compareTo(interval) >= 0)) { + refresh.request(); + } + } + + private void fetch() { + String target; + long expected; + synchronized (lock) { + target = server.get(); + expected = epoch.getAsLong(); + } + if (target == null) { + return; + } + List listed = list(target); + synchronized (lock) { + if (expected != epoch.getAsLong() || !degraded.getAsBoolean()) { + return; + } + record(listed); + } + } + + private List list(String target) { + try { + return serverApiService.listBackups(target); + } catch (RuntimeException e) { + LOGGER.debug("{} did not list its backups: {}", target, e.getMessage()); + return null; + } + } + + private void record(List listed) { + checkedAt = clock.instant(); + if (listed == null) { + return; + } + if (seen != null && !listed.equals(seen)) { + events.publish("backups-changed", Map.of("at", clock.instant().toString())); + } + seen = listed; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java new file mode 100644 index 0000000..f9e45d1 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientEventPublisher.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.service; + +public interface ClientEventPublisher { + + void publish(String name, String data); +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java new file mode 100644 index 0000000..4280849 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientPairingService.java @@ -0,0 +1,133 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.Optional; +import java.util.function.LongConsumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.client.ResourceAccessException; + +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; + +@Service +public class ClientPairingService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientPairingService.class); + static final String DEFAULT_NAME = "MediaGarrd Client"; + static final int MAX_CREDENTIAL_LENGTH = 64; + static final int MAX_NAME_LENGTH = 64; + static final String UNREVOKED_WARNING = "The server could not be told to forget this client, so it may still list it as paired. Remove it with DELETE /api/v1/clients/{id} on the server."; + static final String NOT_PAIRED_WARNING = "This client was not paired with the server."; + static final String NO_ID_WARNING = "This client has no id on the server, so it could not be removed there. Remove it with DELETE /api/v1/clients/{id} on the server."; + static final String ALREADY_PAIRED_MESSAGE = "This client is already paired with this server. Unpair it first."; + static final String DEFERRED_CONFIRMATION_NOTE = "Paired. The server could not be reached to confirm it yet; it is confirmed automatically on the next connection. If it is not, you will be asked to pair again, and the same PIN, or a new pairing code, will work."; + static final long[] CONFIRM_RETRY_DELAYS_MILLIS = {250, 500, 1000}; + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + private final LongConsumer pause; + + @Autowired + public ClientPairingService(ClientStateService stateService, ServerApiService serverApiService) { + this(stateService, serverApiService, ClientPairingService::sleep); + } + + ClientPairingService(ClientStateService stateService, ServerApiService serverApiService, LongConsumer pause) { + this.stateService = stateService; + this.serverApiService = serverApiService; + this.pause = pause; + } + + public synchronized PairingResultDto pair(String credential, String name) { + if (credential == null || credential.isBlank()) { + throw new InvalidRequestException("Enter the PIN or pairing code"); + } + if (credential.trim().length() > MAX_CREDENTIAL_LENGTH) { + throw new InvalidRequestException("The PIN or pairing code must be at most " + MAX_CREDENTIAL_LENGTH + " characters"); + } + if (name != null && name.trim().length() > MAX_NAME_LENGTH) { + throw new InvalidRequestException("The name must be at most " + MAX_NAME_LENGTH + " characters"); + } + String server = stateService.requireActiveServer(); + refuseWhileAlreadyPaired(server); + StoredPairing pairing = serverApiService.pair(server, credential.trim(), name == null || name.isBlank() ? DEFAULT_NAME : name.trim()); + stateService.storePairing(server, pairing); + try { + confirm(server, pairing); + } catch (InvalidRequestException | ConfirmationRefusedException e) { + stateService.forgetPairingIf(server, pairing.token()); + throw e; + } catch (RuntimeException e) { + LOGGER.warn("Could not confirm the pairing with {}, keeping it for the next connection to confirm: {}", server, e.getMessage()); + return new PairingResultDto(true, pairing.name(), DEFERRED_CONFIRMATION_NOTE); + } + return new PairingResultDto(true, pairing.name(), null); + } + + private void refuseWhileAlreadyPaired(String server) { + Optional stored = stateService.pairingFor(server); + if (stored.isEmpty()) { + return; + } + try { + serverApiService.confirmPairing(server, stored.get().token()); + } catch (InvalidRequestException e) { + return; + } + throw new ConflictException(ALREADY_PAIRED_MESSAGE); + } + + public PairingCodeDto createCode() { + return serverApiService.createPairingCode(stateService.requireActiveServer()); + } + + public synchronized UnpairResultDto unpair() { + String server = stateService.requireActiveServer(); + StoredPairing pairing = stateService.pairingFor(server).orElse(null); + String warning = null; + if (pairing != null && hasId(pairing)) { + try { + serverApiService.revokeClient(server, pairing.id()); + } catch (RuntimeException e) { + LOGGER.warn("Could not revoke this client on {}, forgetting the token locally anyway: {}", server, e.getMessage()); + warning = UNREVOKED_WARNING; + } + } else { + warning = pairing == null ? NOT_PAIRED_WARNING : NO_ID_WARNING; + } + stateService.forgetPairing(server); + return new UnpairResultDto(warning == null, warning); + } + + private void confirm(String server, StoredPairing pairing) { + for (int attempt = 0; ; attempt++) { + try { + serverApiService.confirmPairing(server, pairing.token()); + return; + } catch (ResourceAccessException | ConfirmationUnavailableException e) { + if (attempt >= CONFIRM_RETRY_DELAYS_MILLIS.length) { + throw e; + } + LOGGER.warn("Could not confirm the pairing with {}, retrying: {}", server, e.getMessage()); + pause.accept(CONFIRM_RETRY_DELAYS_MILLIS[attempt]); + } + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new UpstreamResponseException("Pairing was interrupted before the server confirmed it"); + } + } + + private static boolean hasId(StoredPairing pairing) { + return pairing.id() != null && !pairing.id().isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java index d6cb990..3c07c59 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -4,34 +4,44 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Collection; import java.time.Duration; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import org.springframework.web.server.ResponseStatusException; +import org.springframework.util.StringUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.core.JacksonException; +import tools.jackson.core.exc.JacksonIOException; +import tools.jackson.databind.ObjectMapper; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; @Service -public class ClientStateService { +public class ClientStateService implements ServerTokens { private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); private static final Duration DEFAULT_PICKUP_INTERVAL = Duration.ofHours(12); + static final Duration MAX_PICKUP_INTERVAL = Duration.ofDays(365); + private static final DateTimeFormatter ASIDE_STAMP = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssSSS").withZone(ZoneOffset.UTC); @JsonIgnoreProperties(ignoreUnknown = true) - record ClientState(String activeServer, long pickupIntervalSeconds, List knownServers) { + record ClientState(String activeServer, long pickupIntervalSeconds, Instant lastPickupAt, List knownServers, Map pairings) { } private final Path statePath; @@ -39,15 +49,24 @@ record ClientState(String activeServer, long pickupIntervalSeconds, List private final Set knownServers = new LinkedHashSet<>(); private final List> activeServerListeners = new CopyOnWriteArrayList<>(); private final List knownServersListeners = new CopyOnWriteArrayList<>(); + private final List> pairingListeners = new CopyOnWriteArrayList<>(); + private final Map pairings = new LinkedHashMap<>(); private String activeServer; private Duration pickupInterval; + private Instant lastPickupAt; - public ClientStateService(Configuration configuration, ObjectMapper mapper) { + public ClientStateService(MediaGarrdProperties configuration, ObjectMapper mapper) { this.statePath = Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); this.mapper = mapper; - this.pickupInterval = valid(configuration.getPickupInterval()) ? configuration.getPickupInterval() : DEFAULT_PICKUP_INTERVAL; + Duration configured = configuration.getPickupInterval(); + if (valid(configured)) { + this.pickupInterval = configured; + } else { + LOGGER.warn("The configured pickup interval {} is outside 1 second to 365 days, using {}", configured, DEFAULT_PICKUP_INTERVAL); + this.pickupInterval = DEFAULT_PICKUP_INTERVAL; + } load(); - LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}", activeServer, pickupInterval, knownServers); + LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}, pairedServers={}", activeServer, pickupInterval, knownServers, pairings.size()); } public synchronized String getActiveServer() { @@ -55,8 +74,8 @@ public synchronized String getActiveServer() { } public synchronized String requireActiveServer() { - if (isBlank(activeServer)) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); + if (!StringUtils.hasText(activeServer)) { + throw new InvalidRequestException("No active MediaGarrd server selected"); } return activeServer; } @@ -65,6 +84,19 @@ public synchronized Duration getPickupInterval() { return pickupInterval; } + public synchronized Instant getLastPickupAt() { + return lastPickupAt; + } + + public synchronized boolean recordPickup(String server, Instant at) { + if (!Objects.equals(server, activeServer)) { + return false; + } + persist(activeServer, pickupInterval, knownServers, pairings, at); + lastPickupAt = at; + return true; + } + public synchronized List getKnownServers() { return List.copyOf(knownServers); } @@ -78,17 +110,22 @@ public void updateKnownServers(List servers) { synchronized (this) { before = activeServer; listBefore = List.copyOf(knownServers); - knownServers.clear(); - knownServers.addAll(servers); - if (isBlank(activeServer)) { - activeServer = knownServers.stream().findFirst().orElse(null); + List found = servers.stream().map(ServerUrls::normalize).toList(); + Set nextKnown = new LinkedHashSet<>(knownServers); + nextKnown.addAll(found); + String nextActive = activeServer; + if (!StringUtils.hasText(nextActive)) { + nextActive = found.stream().findFirst().orElse(null); } else { - knownServers.add(activeServer); + nextKnown.add(nextActive); } + persist(nextActive, pickupInterval, nextKnown, pairings, lastPickupAt); + knownServers.clear(); + knownServers.addAll(nextKnown); + activeServer = nextActive; after = activeServer; listAfter = List.copyOf(knownServers); LOGGER.info("Known servers updated: {}, active server: {}", knownServers, activeServer); - save(); } } finally { if (!Objects.equals(before, after)) { @@ -100,18 +137,24 @@ public void updateKnownServers(List servers) { } } - public void setActiveServer(String serverUrl) { + public void setActiveServer(String requested) { + String serverUrl = ServerUrls.normalize(requested); 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); + Set nextKnown = new LinkedHashSet<>(knownServers); + if (StringUtils.hasText(serverUrl)) { + listChanged = nextKnown.add(serverUrl); } - save(); + Instant nextPickup = changed ? null : lastPickupAt; + persist(serverUrl, pickupInterval, nextKnown, pairings, nextPickup); + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + activeServer = serverUrl; + lastPickupAt = nextPickup; + knownServers.clear(); + knownServers.addAll(nextKnown); } } finally { if (changed) { @@ -123,19 +166,25 @@ public void setActiveServer(String serverUrl) { } } - public void setActiveServerIfBlank(String serverUrl) { + public void setActiveServerIfBlank(String requested) { + String serverUrl = ServerUrls.normalize(requested); boolean changed = false; boolean listChanged = false; try { synchronized (this) { - if (!isBlank(activeServer) || isBlank(serverUrl)) { + if (StringUtils.hasText(activeServer) || !StringUtils.hasText(serverUrl)) { return; } + Set nextKnown = new LinkedHashSet<>(knownServers); + listChanged = nextKnown.add(serverUrl); + Instant nextPickup = changed ? null : lastPickupAt; + persist(serverUrl, pickupInterval, nextKnown, pairings, nextPickup); LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); activeServer = serverUrl; + lastPickupAt = nextPickup; changed = true; - listChanged = knownServers.add(serverUrl); - save(); + knownServers.clear(); + knownServers.addAll(nextKnown); } } finally { if (changed) { @@ -147,6 +196,10 @@ public void setActiveServerIfBlank(String serverUrl) { } } + public synchronized boolean isKnownServer(String serverUrl) { + return knownServers.contains(ServerUrls.normalize(serverUrl)); + } + public void addActiveServerListener(Consumer listener) { activeServerListeners.add(listener); } @@ -155,6 +208,78 @@ public void addKnownServersListener(Runnable listener) { knownServersListeners.add(listener); } + public void addPairingListener(Consumer listener) { + pairingListeners.add(listener); + } + + @Override + public synchronized Optional tokenFor(String serverUrl) { + return pairingFor(serverUrl).map(StoredPairing::token); + } + + public synchronized Optional pairingFor(String serverUrl) { + return Optional.ofNullable(pairings.get(ServerUrls.normalize(serverUrl))); + } + + public synchronized boolean hasPairing(String serverUrl) { + return pairings.containsKey(ServerUrls.normalize(serverUrl)); + } + + public void storePairing(String serverUrl, StoredPairing pairing) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + Map next = new LinkedHashMap<>(pairings); + next.put(key, pairing); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + LOGGER.info("Paired with {} as {}", key, pairing.name()); + pairings.put(key, pairing); + } + notifyPairingListeners(key); + } + + public boolean forgetPairing(String serverUrl) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + if (!pairings.containsKey(key)) { + return false; + } + Map next = new LinkedHashMap<>(pairings); + next.remove(key); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + pairings.remove(key); + LOGGER.info("Forgot the pairing with {}", key); + } + notifyPairingListeners(key); + return true; + } + + public boolean forgetPairingIf(String serverUrl, String token) { + String key = ServerUrls.normalize(serverUrl); + synchronized (this) { + StoredPairing current = pairings.get(key); + if (current == null || !current.token().equals(token)) { + return false; + } + Map next = new LinkedHashMap<>(pairings); + next.remove(key); + persist(activeServer, pickupInterval, knownServers, next, lastPickupAt); + pairings.remove(key); + LOGGER.info("Forgot the pairing with {}", key); + } + notifyPairingListeners(key); + return true; + } + + private void notifyPairingListeners(String serverUrl) { + for (Consumer listener : pairingListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Pairing listener failed: {}", e.getMessage()); + } + } + } + private void notifyKnownServersListeners() { for (Runnable listener : knownServersListeners) { try { @@ -176,12 +301,15 @@ private void notifyActiveServerListeners(String serverUrl) { } public synchronized Duration setPickupInterval(Duration interval) { - if (!valid(interval)) { - throw new IllegalArgumentException("Pickup interval must be a positive duration"); + if (interval == null || !interval.isPositive()) { + throw new InvalidRequestException("Pickup interval must be a positive duration"); } + if (interval.compareTo(MAX_PICKUP_INTERVAL) > 0) { + throw new InvalidRequestException("Pickup interval must be at most 365 days"); + } + persist(activeServer, interval, knownServers, pairings, lastPickupAt); pickupInterval = interval; LOGGER.info("Pickup interval updated to {}", interval); - save(); return interval; } @@ -190,38 +318,75 @@ private void load() { LOGGER.info("No state file at {}, starting fresh", statePath); return; } + if (!Files.isReadable(statePath)) { + throw unreadable(null); + } try { ClientState state = mapper.readValue(statePath.toFile(), ClientState.class); + if (state == null) { + throw new IllegalStateException("the file is empty"); + } if (state.knownServers() != null) { - knownServers.addAll(state.knownServers()); + state.knownServers().stream().map(ServerUrls::normalize).forEach(knownServers::add); } - activeServer = isBlank(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : state.activeServer(); + if (state.pairings() != null) { + state.pairings().forEach((url, pairing) -> { + if (pairing != null && StringUtils.hasText(pairing.token())) { + pairings.put(ServerUrls.normalize(url), pairing); + } + }); + } + activeServer = !StringUtils.hasText(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : ServerUrls.normalize(state.activeServer()); Duration saved = Duration.ofSeconds(state.pickupIntervalSeconds()); if (valid(saved)) { pickupInterval = saved; + } else if (state.pickupIntervalSeconds() != 0) { + LOGGER.warn("Ignoring the stored pickup interval of {} seconds, it is outside 1 second to 365 days. Using {}", state.pickupIntervalSeconds(), pickupInterval); } - } catch (IOException e) { - LOGGER.warn("Could not read state from {}, starting with defaults: {}", statePath, e.getMessage()); + lastPickupAt = state.lastPickupAt(); + } catch (JacksonIOException e) { + throw unreadable(e); + } catch (JacksonException | IllegalStateException e) { + moveAside(e); + } + } + + private IllegalStateException unreadable(Exception cause) { + String detail = cause == null ? "it is not readable" : cause.getMessage(); + return new IllegalStateException("Could not read the client state file " + statePath + " as " + runUser() + ": " + detail + + ". Fix its owner or permissions so that this user can read it (or run the container with the matching PUID and PGID); the file is left untouched", cause); + } + + private static String runUser() { + try { + return "UID " + Files.getAttribute(Path.of("/proc/self"), "unix:uid"); + } catch (IOException | RuntimeException e) { + return "user " + System.getProperty("user.name"); } } - private void save() { + private void moveAside(Exception cause) { + Path aside = statePath.resolveSibling(statePath.getFileName() + ".corrupt-" + ASIDE_STAMP.format(Instant.now())); try { - Files.createDirectories(statePath.getParent()); - Path temp = statePath.resolveSibling(statePath.getFileName() + ".tmp"); - ClientState state = new ClientState(activeServer == null ? "" : activeServer, pickupInterval.toSeconds(), new ArrayList<>(knownServers)); - mapper.writerWithDefaultPrettyPrinter().writeValue(temp.toFile(), state); - Files.move(temp, statePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + Files.move(statePath, aside, StandardCopyOption.REPLACE_EXISTING); + LOGGER.error("Could not read the client state from {} ({}). The file was moved to {} and the client starts without pairings, so every server needs to be paired again", + statePath, cause.getMessage(), aside); } catch (IOException e) { - throw new IllegalStateException("Failed to save client state to " + statePath, e); + LOGGER.error("Could not read the client state from {} ({}) and could not move it aside ({}). The client starts without pairings and the next change overwrites the file", + statePath, cause.getMessage(), e.getMessage()); } } - private static boolean valid(Duration duration) { - return duration != null && duration.isPositive(); + private void persist(String active, Duration interval, Collection known, Map paired, Instant lastPickup) { + try { + ClientState state = new ClientState(active == null ? "" : active, interval.toSeconds(), lastPickup, new ArrayList<>(known), new LinkedHashMap<>(paired)); + OwnerOnlyFiles.write(statePath, mapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(state)); + } catch (IOException | JacksonException e) { + throw new IllegalStateException("Failed to save client state to " + statePath, e); + } } - private static boolean isBlank(String value) { - return value == null || value.isBlank(); + private static boolean valid(Duration duration) { + return duration != null && duration.isPositive() && duration.compareTo(MAX_PICKUP_INTERVAL) <= 0; } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java b/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java new file mode 100644 index 0000000..e70bceb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/CoalescedRefresh.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class CoalescedRefresh { + + private static final Logger LOGGER = LoggerFactory.getLogger(CoalescedRefresh.class); + + private final Object lock; + private final Executor executor; + private final Runnable work; + private boolean inFlight; + private boolean again; + + CoalescedRefresh(Object lock, Executor executor, Runnable work) { + this.lock = lock; + this.executor = executor; + this.work = work; + } + + void request() { + synchronized (lock) { + if (inFlight) { + again = true; + return; + } + inFlight = true; + } + try { + executor.execute(this::loop); + } catch (RejectedExecutionException e) { + synchronized (lock) { + inFlight = false; + } + } + } + + boolean busy() { + return inFlight; + } + + 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); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java new file mode 100644 index 0000000..0c4c905 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationRefusedException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConfirmationRefusedException extends UpstreamResponseException { + + public ConfirmationRefusedException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java new file mode 100644 index 0000000..4d3261b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConfirmationUnavailableException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConfirmationUnavailableException extends UpstreamResponseException { + + public ConfirmationUnavailableException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java new file mode 100644 index 0000000..86ee3d2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ConflictException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ConflictException extends RuntimeException { + + public ConflictException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java new file mode 100644 index 0000000..15068d2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardEvents.java @@ -0,0 +1,31 @@ +package wellatleastitried.mediagarrdclient.service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +final class DashboardEvents { + + private final ClientEventPublisher publisher; + private final ObjectMapper mapper; + + DashboardEvents(ClientEventPublisher publisher, ObjectMapper mapper) { + this.publisher = publisher; + this.mapper = mapper; + } + + void publish(String name, Object payload) { + publisher.publish(name, json(payload)); + } + + void publishRaw(String name, String data) { + publisher.publish(name, data); + } + + String json(Object payload) { + try { + return mapper.writeValueAsString(payload); + } catch (JacksonException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java index a20689b..9984534 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DashboardService.java @@ -8,10 +8,12 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.concurrent.CopyOnWriteArrayList; 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; @@ -19,17 +21,15 @@ 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 tools.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.PairingState; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; @Service @@ -39,82 +39,30 @@ public class DashboardService { 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 ServerApiService serverApiService; 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 final List> recoveryListeners = new CopyOnWriteArrayList<>(); + private final DashboardEvents events; + private final PairingStatus pairingStatus; + private final LinkStateMachine links; + private final BackupWatcher backups; + private final CoalescedRefresh healthRefresh; + private final CoalescedRefresh versionRefresh; 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, + ClientEventPublisher broadcaster, ServerApiService serverApiService, VersionService versionService, UpdateCheckService updateCheckService, @@ -125,7 +73,7 @@ public DashboardService( DashboardService( ClientStateService stateService, - ClientEventBroadcaster broadcaster, + ClientEventPublisher broadcaster, ServerApiService serverApiService, VersionService versionService, UpdateCheckService updateCheckService, @@ -134,13 +82,17 @@ public DashboardService( 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; + this.events = new DashboardEvents(broadcaster, mapper); + this.pairingStatus = new PairingStatus(stateService, events); + this.links = new LinkStateMachine(events, clock); + this.backups = new BackupWatcher(serverApiService, events, clock, lock, executor, CATCH_ALL_INTERVAL, () -> activeServer, () -> epoch, () -> links.link() == LinkState.DEGRADED); + this.healthRefresh = new CoalescedRefresh(lock, executor, this::fetchHealth); + this.versionRefresh = new CoalescedRefresh(lock, executor, this::fetchVersion); } private static ExecutorService refreshThreads() { @@ -151,6 +103,9 @@ private static ExecutorService refreshThreads() { @PostConstruct void start() { stateService.addKnownServersListener(this::sync); + stateService.addActiveServerListener(ignored -> sync()); + stateService.addPairingListener(this::pairingChanged); + serverApiService.addTokenRejectedListener(this::pairingRejected); updateCheckService.addStatusListener(ignored -> publishVersions()); sync(); } @@ -168,31 +123,19 @@ public DashboardState state() { } } - public Optional subscribe() { + public Optional subscribe(Function, Optional> registration) { synchronized (lock) { - return broadcaster.subscribe(List.of(new ClientEvent("snapshot", json(snapshot())))); + return registration.apply(List.of(new ClientEvent("snapshot", events.json(snapshot())))); } } void sync() { synchronized (lock) { - String active = normalize(stateService.getActiveServer()); + String active = ServerUrls.nullIfBlank(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(); - } + reset(active); } else if (!known.equals(knownServers)) { knownServers = known; publishServers(); @@ -200,12 +143,44 @@ void sync() { } } + private void reset(String active) { + activeServer = active; + links.reset(active != null); + health = null; + healthFetchedAt = null; + backups.forget(); + pairingStatus.clear(); + epoch++; + versionService.select(active); + events.publish("snapshot", snapshot()); + if (active != null) { + healthRefresh.request(); + } + } + + void pairingChanged(String server) { + synchronized (lock) { + if (Objects.equals(ServerUrls.nullIfBlank(server), activeServer)) { + reset(activeServer); + } + } + } + + void pairingRejected(String server) { + synchronized (lock) { + if (!Objects.equals(server, activeServer)) { + return; + } + pairingStatus.reject(activeServer); + } + } + void streamUp(String server) { synchronized (lock) { if (!Objects.equals(server, activeServer)) { return; } - boolean wasDown = link == LinkState.DOWN; + boolean wasDown = links.link() == LinkState.DOWN; setLink(LinkState.LIVE); healthRefresh.request(); if (versionService.invalidate(wasDown)) { @@ -229,15 +204,15 @@ void runEvent(String server, String name, String data, boolean runningNow) { if (!Objects.equals(server, activeServer)) { return; } - running = runningNow; - broadcaster.publish(name, data); + links.setRunning(runningNow); + events.publishRaw(name, data); } } void backupsChanged(String server, String data) { synchronized (lock) { if (Objects.equals(server, activeServer)) { - broadcaster.publish("backups-changed", data); + events.publishRaw("backups-changed", data); } } } @@ -256,20 +231,24 @@ void tick() { if (activeServer == null) { return; } - Duration limit = link == LinkState.LIVE ? CATCH_ALL_INTERVAL : POLL_INTERVAL; + Duration limit = links.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()) { + if (links.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(); + if (links.link() == LinkState.DEGRADED) { + backups.requestWhenDue(); } } } + public void addRecoveryListener(Consumer listener) { + recoveryListeners.add(listener); + } + private void fetchHealth() { String server; long expected; @@ -281,80 +260,68 @@ private void fetchHealth() { return; } ServerStatusDto status = null; + boolean tokenRejected = false; try { status = serverApiService.health(server); + } catch (PairingRequiredException e) { + tokenRejected = true; + status = new ServerStatusDto(true, false, 0, null); } catch (RuntimeException e) { LOGGER.debug("{} did not answer the health check: {}", server, e.getMessage()); } - applyHealth(expected, status); + applyHealth(expected, status, tokenRejected); } - private void applyHealth(long expected, ServerStatusDto status) { + private void applyHealth(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared; 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(); - } + cleared = applyHealthLocked(expected, status, tokenRejected); + } + if (cleared != null) { + for (Consumer listener : recoveryListeners) { + listener.accept(cleared); } } } - private void fetchBackups() { - String server; - long expected; - synchronized (lock) { - server = activeServer; - expected = epoch; + private String applyHealthLocked(long expected, ServerStatusDto status, boolean tokenRejected) { + String cleared = null; + if (expected != epoch) { + return null; } - if (server == null) { - return; + healthFetchedAt = clock.instant(); + if (status != null && pairingStatus.observe(tokenRejected, activeServer)) { + cleared = activeServer; } - List listed; - try { - listed = serverApiService.listBackups(server); - } catch (RuntimeException e) { - LOGGER.debug("{} did not list its backups: {}", server, e.getMessage()); - listed = null; + boolean detailed = status != null && pairingStatus.of(activeServer) == PairingState.PAIRED; + if (status == null) { + if (links.link() != LinkState.LIVE) { + setLink(LinkState.DOWN); + if (versionService.markUnreachable()) { + events.publish("versions", versionService.versions()); + } + } + return cleared; } - synchronized (lock) { - if (expected != epoch || link != LinkState.DEGRADED) { - return; + if (detailed) { + HealthSummary summary = new HealthSummary(status.backupInterval(), status.backupRetentionCount()); + if (!summary.equals(health)) { + health = summary; + events.publish("config", summary); } - backupsCheckedAt = clock.instant(); - if (listed == null) { - return; + } + if (links.link() != LinkState.LIVE) { + boolean recovered = links.link() != LinkState.DEGRADED; + boolean wasDown = links.link() == LinkState.DOWN; + setLink(LinkState.DEGRADED); + if (detailed && links.setPolledRunning(status.running())) { + backups.forgetListing(); } - if (backupsSeen != null && !listed.equals(backupsSeen)) { - broadcaster.publish("backups-changed", json(Map.of("at", clock.instant().toString()))); + if (recovered && versionService.invalidate(wasDown)) { + versionRefresh.request(); } - backupsSeen = listed; } - } - - private boolean reachable() { - return link == LinkState.LIVE || link == LinkState.DEGRADED; + return cleared; } private void fetchVersion() { @@ -365,7 +332,7 @@ private void fetchVersion() { private void publishVersions() { synchronized (lock) { - broadcaster.publish("versions", json(versionService.versions())); + events.publish("versions", versionService.versions()); } } @@ -373,54 +340,16 @@ private void publishServers() { Map payload = new LinkedHashMap<>(); payload.put("knownServers", knownServers); payload.put("activeServer", activeServer); - broadcaster.publish("servers", json(payload)); + events.publish("servers", payload); } private void setLink(LinkState next) { - if (link == next) { - return; + if (links.setLink(next, activeServer) && next != LinkState.DEGRADED) { + backups.forget(); } - 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; + return new DashboardState(activeServer, knownServers, links.link(), links.running(), health, versionService.versions(), pairingStatus.of(activeServer)); } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java new file mode 100644 index 0000000..1e5feb4 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/DownloadFailedException.java @@ -0,0 +1,12 @@ +package wellatleastitried.mediagarrdclient.service; + +public class DownloadFailedException extends RuntimeException { + + public DownloadFailedException(String message) { + super(message); + } + + public DownloadFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java new file mode 100644 index 0000000..3425a99 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/InvalidRequestException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class InvalidRequestException extends RuntimeException { + + public InvalidRequestException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java b/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java new file mode 100644 index 0000000..4a71252 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/LinkStateMachine.java @@ -0,0 +1,69 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.util.LinkedHashMap; +import java.util.Map; + +import wellatleastitried.mediagarrdclient.dto.LinkState; + +final class LinkStateMachine { + + private final DashboardEvents events; + private final Clock clock; + private LinkState link = LinkState.DOWN; + private Boolean running; + + LinkStateMachine(DashboardEvents events, Clock clock) { + this.events = events; + this.clock = clock; + } + + LinkState link() { + return link; + } + + Boolean running() { + return running; + } + + boolean reachable() { + return link == LinkState.LIVE || link == LinkState.DEGRADED; + } + + void reset(boolean serverSelected) { + link = serverSelected ? LinkState.CONNECTING : LinkState.DOWN; + running = null; + } + + void setRunning(boolean now) { + running = now; + } + + boolean setLink(LinkState next, String activeServer) { + if (link == next) { + return false; + } + link = next; + if (!reachable()) { + running = null; + } + Map payload = new LinkedHashMap<>(); + payload.put("server", activeServer == null ? "" : activeServer); + payload.put("state", next); + events.publish("link", payload); + return true; + } + + boolean setPolledRunning(boolean polled) { + if (Boolean.valueOf(polled).equals(running)) { + return false; + } + boolean runFinished = Boolean.TRUE.equals(running) && !polled; + running = polled; + Map payload = new LinkedHashMap<>(); + payload.put("running", polled); + payload.put("at", clock.instant().toString()); + events.publish("state", payload); + return runFinished; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java b/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java new file mode 100644 index 0000000..2f1b078 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/LoginAttempts.java @@ -0,0 +1,131 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class LoginAttempts { + + static final int FREE_FAILURES = 3; + static final Duration FIRST_LOCK = Duration.ofSeconds(5); + static final Duration MAX_LOCK = Duration.ofMinutes(5); + static final Duration FORGET_AFTER = Duration.ofHours(1); + static final int MAX_TRACKED = 1000; + static final int BUCKET_CAPACITY = 30; + static final Duration BUCKET_REFILL_PERIOD = Duration.ofMinutes(1); + public static final Duration BUSY_RETRY = Duration.ofSeconds(1); + + private static final class Record { + private int failures; + private Instant lockedUntil = Instant.MIN; + private Instant lastFailure = Instant.MIN; + } + + private final Clock clock; + private final int maxTracked; + private final Map records = new LinkedHashMap<>(); + private final Set inFlight = new HashSet<>(); + private double tokens = BUCKET_CAPACITY; + private Instant lastRefill; + + @Autowired + public LoginAttempts() { + this(Clock.systemUTC(), MAX_TRACKED); + } + + LoginAttempts(Clock clock, int maxTracked) { + this.clock = clock; + this.maxTracked = maxTracked; + this.lastRefill = clock.instant(); + } + + public synchronized Optional tryBegin(String source) { + Optional locked = lockedFor(source); + if (locked.isPresent()) { + return locked; + } + if (!inFlight.add(source)) { + return Optional.of(BUSY_RETRY); + } + refill(); + if (tokens < 1) { + inFlight.remove(source); + double missing = 1 - tokens; + return Optional.of(Duration.ofNanos((long) Math.ceil(missing * BUCKET_REFILL_PERIOD.toNanos() / BUCKET_CAPACITY))); + } + tokens -= 1; + return Optional.empty(); + } + + public synchronized void abandon(String source) { + if (inFlight.remove(source)) { + refund(); + } + } + + private void refill() { + Instant now = clock.instant(); + if (now.isAfter(lastRefill)) { + double elapsed = Duration.between(lastRefill, now).toNanos(); + tokens = Math.min(BUCKET_CAPACITY, tokens + elapsed * BUCKET_CAPACITY / BUCKET_REFILL_PERIOD.toNanos()); + lastRefill = now; + } + } + + private void refund() { + refill(); + tokens = Math.min(BUCKET_CAPACITY, tokens + 1); + } + + public synchronized Optional lockedFor(String source) { + Record record = records.get(source); + if (record == null) { + return Optional.empty(); + } + Instant now = clock.instant(); + if (Duration.between(record.lastFailure, now).compareTo(FORGET_AFTER) >= 0) { + records.remove(source); + return Optional.empty(); + } + if (now.isBefore(record.lockedUntil)) { + return Optional.of(Duration.between(now, record.lockedUntil)); + } + return Optional.empty(); + } + + public synchronized void failed(String source) { + Instant now = clock.instant(); + inFlight.remove(source); + Record record = records.remove(source); + if (record == null || Duration.between(record.lastFailure, now).compareTo(FORGET_AFTER) >= 0) { + record = new Record(); + } + while (records.size() >= maxTracked) { + records.remove(records.keySet().iterator().next()); + } + record.failures++; + record.lastFailure = now; + if (record.failures > FREE_FAILURES) { + long doublings = Math.min(record.failures - FREE_FAILURES - 1, 20); + Duration lock = FIRST_LOCK.multipliedBy(1L << doublings); + record.lockedUntil = now.plus(lock.compareTo(MAX_LOCK) > 0 ? MAX_LOCK : lock); + } + records.put(source, record); + } + + public synchronized void succeeded(String source) { + if (inFlight.remove(source)) { + refund(); + } + records.remove(source); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java new file mode 100644 index 0000000..648fb5c --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/NoBackupsException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class NoBackupsException extends NotFoundException { + + public NoBackupsException() { + super("No backups found on server"); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java new file mode 100644 index 0000000..1dd1480 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/NotFoundException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class NotFoundException extends RuntimeException { + + public NotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java b/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java new file mode 100644 index 0000000..65d493d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/OwnerOnlyFiles.java @@ -0,0 +1,50 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; + +final class OwnerOnlyFiles { + + private OwnerOnlyFiles() { + } + + static void write(Path target, byte[] content) throws IOException { + Files.createDirectories(target.getParent()); + Path temp = target.resolveSibling(target.getFileName() + ".tmp"); + Files.deleteIfExists(temp); + try { + Files.createFile(temp, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException e) { + Files.createFile(temp); + } + try { + Files.write(temp, content); + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temp); + } + } + + static void createDirectories(Path directory) throws IOException { + try { + Files.createDirectories(directory, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + } catch (UnsupportedOperationException e) { + Files.createDirectories(directory); + } + } + + static OutputStream newOutputStream(Path file) throws IOException { + Files.deleteIfExists(file); + try { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException e) { + Files.createFile(file); + } + return Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java new file mode 100644 index 0000000..8a883e5 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingRequiredException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class PairingRequiredException extends RuntimeException { + + public PairingRequiredException(String message) { + super(message); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java new file mode 100644 index 0000000..68230d6 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PairingStatus.java @@ -0,0 +1,56 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.LinkedHashMap; +import java.util.Map; + +import wellatleastitried.mediagarrdclient.dto.PairingState; + +final class PairingStatus { + + private final ClientStateService stateService; + private final DashboardEvents events; + private boolean rejected; + + PairingStatus(ClientStateService stateService, DashboardEvents events) { + this.stateService = stateService; + this.events = events; + } + + PairingState of(String activeServer) { + if (activeServer == null) { + return PairingState.NONE; + } + if (!stateService.hasPairing(activeServer)) { + return PairingState.REQUIRED; + } + return rejected ? PairingState.REJECTED : PairingState.PAIRED; + } + + void clear() { + rejected = false; + } + + void reject(String activeServer) { + if (rejected) { + return; + } + rejected = true; + publish(activeServer); + } + + boolean observe(boolean tokenRejected, String activeServer) { + if (tokenRejected == rejected) { + return false; + } + boolean cleared = rejected && !tokenRejected; + rejected = tokenRejected; + publish(activeServer); + return cleared; + } + + private void publish(String activeServer) { + Map payload = new LinkedHashMap<>(); + payload.put("state", of(activeServer)); + events.publish("pairing", payload); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java new file mode 100644 index 0000000..ace68e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PasswordService.java @@ -0,0 +1,158 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@Service +public class PasswordService { + + private static final Logger LOGGER = LoggerFactory.getLogger(PasswordService.class); + static final int ITERATIONS = 600_000; + static final int MIN_LENGTH = 8; + static final int MAX_LENGTH = 256; + private static final int SALT_BYTES = 16; + private static final int HASH_BITS = 256; + private static final String ALGORITHM = "PBKDF2WithHmacSHA256"; + + record StoredHash(int iterations, String salt, String hash) { + } + + private final Path file; + private final ObjectMapper mapper; + private final int iterations; + private final SecureRandom random = new SecureRandom(); + private final StoredHash environment; + private StoredHash stored; + + @Autowired + public PasswordService(MediaGarrdProperties configuration, ObjectMapper mapper) { + this(configuration, mapper, ITERATIONS); + } + + PasswordService(MediaGarrdProperties configuration, ObjectMapper mapper, int iterations) { + this.file = Path.of(configuration.getStateFile()).toAbsolutePath().normalize().resolveSibling("password.json"); + this.mapper = mapper; + this.iterations = iterations; + String fromEnvironment = configuration.getPassword(); + this.environment = fromEnvironment == null || fromEnvironment.isEmpty() ? null : hash(fromEnvironment, iterations); + if (configuration.isResetPassword()) { + reset(); + } + this.stored = load(); + if (environment != null) { + LOGGER.info("The dashboard password comes from CLIENT_PASSWORD"); + } else if (stored == null) { + LOGGER.warn("No dashboard password is set, the first person to open the dashboard can set it"); + } + } + + public boolean isConfigured() { + return environment != null || currentStored() != null; + } + + public boolean isFromEnvironment() { + return environment != null; + } + + public boolean matches(String password) { + StoredHash expected = environment != null ? environment : currentStored(); + if (expected == null || password == null || password.length() > MAX_LENGTH) { + return false; + } + byte[] actual = derive(password, Base64.getDecoder().decode(expected.salt()), expected.iterations()); + return MessageDigest.isEqual(actual, Base64.getDecoder().decode(expected.hash())); + } + + public synchronized void setInitial(String password) { + if (environment != null) { + throw new ConflictException("The password is set by CLIENT_PASSWORD and cannot be changed here"); + } + if (stored != null) { + throw new ConflictException("A password is already set"); + } + if (password == null || password.length() < MIN_LENGTH) { + throw new InvalidRequestException("The password must be at least " + MIN_LENGTH + " characters"); + } + if (password.length() > MAX_LENGTH) { + throw new InvalidRequestException("The password must be at most " + MAX_LENGTH + " characters"); + } + StoredHash created = hash(password, iterations); + try { + OwnerOnlyFiles.write(file, mapper.writeValueAsBytes(created)); + } catch (IOException | JacksonException e) { + throw new IllegalStateException("Failed to save the dashboard password to " + file, e); + } + stored = created; + LOGGER.info("The dashboard password was set"); + } + + private synchronized StoredHash currentStored() { + return stored; + } + + private void reset() { + try { + if (Files.deleteIfExists(file)) { + LOGGER.warn("CLIENT_RESET_PASSWORD is set: the stored dashboard password was removed, the first person to open the dashboard can set a new one. Remove CLIENT_RESET_PASSWORD now"); + } else { + LOGGER.warn("CLIENT_RESET_PASSWORD is set but no password was stored. Remove it"); + } + } catch (IOException e) { + throw new IllegalStateException("Could not remove the stored dashboard password " + file + ": " + e.getMessage(), e); + } + } + + private StoredHash load() { + if (!Files.exists(file)) { + return null; + } + try { + StoredHash loaded = mapper.readValue(file.toFile(), StoredHash.class); + if (loaded == null || loaded.salt() == null || loaded.hash() == null || loaded.iterations() < 1) { + throw new IOException("the file is incomplete"); + } + Base64.getDecoder().decode(loaded.salt()); + Base64.getDecoder().decode(loaded.hash()); + return loaded; + } catch (IOException | IllegalArgumentException | JacksonException e) { + throw new IllegalStateException("Could not read the stored dashboard password " + file + ": " + e.getMessage() + + ". Fix or delete the file, or start once with CLIENT_RESET_PASSWORD=true", e); + } + } + + private StoredHash hash(String password, int rounds) { + byte[] salt = new byte[SALT_BYTES]; + random.nextBytes(salt); + byte[] derived = derive(password, salt, rounds); + return new StoredHash(rounds, Base64.getEncoder().encodeToString(salt), Base64.getEncoder().encodeToString(derived)); + } + + private static byte[] derive(String password, byte[] salt, int rounds) { + PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, rounds, HASH_BITS); + try { + return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).getEncoded(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Password hashing is unavailable: " + e.getMessage(), e); + } finally { + spec.clearPassword(); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java b/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java new file mode 100644 index 0000000..d0ebcfb --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/PickupSchedule.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +final class PickupSchedule { + + static final List BACKOFF = List.of(Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5), Duration.ofMinutes(10), Duration.ofMinutes(15)); + + private final Clock clock; + private int failures; + private Instant retryAt; + + PickupSchedule(Clock clock) { + this.clock = clock; + } + + synchronized boolean due(Instant lastPickup, Duration interval) { + Instant now = clock.instant(); + if (retryAt != null) { + Instant cap = now.plus(BACKOFF.getLast()); + if (retryAt.isAfter(cap)) { + retryAt = cap; + } + if (now.isBefore(retryAt)) { + return false; + } + } + return !now.isBefore(dueAt(lastPickup, interval)); + } + + Instant dueAt(Instant lastPickup, Duration interval) { + Instant now = clock.instant(); + return lastPickup == null || lastPickup.isAfter(now) ? now : lastPickup.plus(interval); + } + + synchronized Instant failed() { + retryAt = clock.instant().plus(BACKOFF.get(Math.min(failures, BACKOFF.size() - 1))); + failures++; + return retryAt; + } + + synchronized void reset() { + failures = 0; + retryAt = null; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java b/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java new file mode 100644 index 0000000..99511a8 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/QuietFiles.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class QuietFiles { + + private static final Logger LOGGER = LoggerFactory.getLogger(QuietFiles.class); + + private QuietFiles() { + } + + static boolean delete(Path path) { + try { + return Files.deleteIfExists(path); + } catch (IOException e) { + LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); + return false; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java new file mode 100644 index 0000000..fc4f898 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicy.java @@ -0,0 +1,47 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Duration; + +final class ReconnectPolicy { + + enum Outcome { + ROLLOVER, + UNSUPPORTED, + REJECTED, + FAILED + } + + record Decision(Outcome outcome, Duration delay) { + } + + private final Duration initialBackoff; + private final Duration maxBackoff; + private final Duration unsupportedRetry; + private final Duration minLifetime; + private Duration backoff; + + ReconnectPolicy(Duration initialBackoff, Duration maxBackoff, Duration unsupportedRetry, Duration minLifetime) { + this.initialBackoff = initialBackoff; + this.maxBackoff = maxBackoff; + this.unsupportedRetry = unsupportedRetry; + this.minLifetime = minLifetime; + this.backoff = initialBackoff; + } + + Decision next(Outcome outcome, boolean eventsSeen, long lifetimeNanos) { + boolean shortLived = lifetimeNanos < minLifetime.toNanos(); + if (eventsSeen && !shortLived) { + backoff = initialBackoff; + } + Outcome effective = outcome == Outcome.ROLLOVER && shortLived ? Outcome.FAILED : outcome; + Duration delay = effective == Outcome.UNSUPPORTED ? unsupportedRetry : backoff; + if (effective == Outcome.FAILED) { + backoff = min(backoff.multipliedBy(2), maxBackoff); + } + return new Decision(effective, delay); + } + + private static Duration min(Duration a, Duration b) { + return a.compareTo(b) <= 0 ? a : b; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java index afa9eb8..1b623cd 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -15,25 +15,44 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; import org.springframework.stereotype.Service; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; import org.springframework.web.util.UriUtils; -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.api.Endpoints; +import jakarta.annotation.PreDestroy; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; import wellatleastitried.mediagarrdclient.dto.ServiceDto; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; @Service public class ServerApiService { @@ -44,25 +63,44 @@ public interface DownloadProgressListener { } private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); + private static final JacksonJsonHttpMessageConverter JSON = new JacksonJsonHttpMessageConverter( + JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)); private static final String SERVICE_PATH = Endpoints.SERVER_SERVICES.getPath() + "/{name}"; 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 Duration DOWNLOAD_STALL_TIMEOUT = Duration.ofSeconds(60); private static final int BUFFER_SIZE = 64 * 1024; - private final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(CONNECT_TIMEOUT) - .followRedirects(HttpClient.Redirect.NORMAL) - .build(); - private final RestClient healthClient = restClient(HEALTH_TIMEOUT); - private final RestClient restClient = restClient(REQUEST_TIMEOUT); + private record ServerError(String error) { + } + + private record PairReply(String token, String id, String name) { + + @Override + public String toString() { + return "PairReply[id=" + id + ", name=" + name + "]"; + } + } + + private record ConfirmReply(boolean healthy, Boolean running, Integer backupRetentionCount, Duration backupInterval) { + } + + private final ServerTokens tokens; + private final HttpClient httpClient; + private final RestClient healthClient; + private final RestClient restClient; private final RestClient backupRunClient; private final Duration backupRunTimeout; + private final Duration stallTimeout; + private final ScheduledExecutorService stallWatchdog = Executors.newSingleThreadScheduledExecutor( + runnable -> Thread.ofPlatform().daemon().name("download-stall-watchdog").unstarted(runnable)); + private final List> tokenRejectedListeners = new CopyOnWriteArrayList<>(); @Autowired - public ServerApiService(Configuration properties) { - this(checked(properties.getBackupRunTimeout())); + public ServerApiService(MediaGarrdProperties properties, ClientStateService stateService, ServerTls tls) { + this(checked(properties.getBackupRunTimeout()), stateService, tls); } private static Duration checked(Duration backupRunTimeout) { @@ -72,8 +110,25 @@ private static Duration checked(Duration backupRunTimeout) { return backupRunTimeout; } - ServerApiService(Duration backupRunTimeout) { + ServerApiService(Duration backupRunTimeout, ServerTokens tokens, ServerTls tls) { + this(backupRunTimeout, DOWNLOAD_STALL_TIMEOUT, tokens, tls); + } + + ServerApiService(Duration backupRunTimeout, Duration stallTimeout, ServerTokens tokens, ServerTls tls) { + this(backupRunTimeout, stallTimeout, HEALTH_TIMEOUT, REQUEST_TIMEOUT, tokens, tls); + } + + ServerApiService(Duration backupRunTimeout, Duration stallTimeout, Duration healthTimeout, Duration requestTimeout, ServerTokens tokens, ServerTls tls) { this.backupRunTimeout = backupRunTimeout; + this.stallTimeout = stallTimeout; + this.tokens = tokens; + this.httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); + this.healthClient = restClient(healthTimeout); + this.restClient = restClient(requestTimeout); this.backupRunClient = restClient(backupRunTimeout); } @@ -82,29 +137,29 @@ private RestClient restClient(Duration readTimeout) { if (readTimeout != null) { requestFactory.setReadTimeout(readTimeout); } - return RestClient.builder().requestFactory(requestFactory).build(); + return RestClient.builder().requestFactory(requestFactory).configureMessageConverters(converters -> converters.withJsonConverter(JSON)).build(); } public ServerStatusDto health(String serverUrl) { - ServerStatusDto status = healthClient.get() - .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) - .retrieve() - .body(ServerStatusDto.class); + RestClient.RequestHeadersSpec request = healthClient.get().uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()); + Optional token = tokens.tokenFor(serverUrl); + if (token.isPresent()) { + request = request.header(HttpHeaders.AUTHORIZATION, "Bearer " + token.get()); + } + ServerStatusDto status = checked(request.retrieve()).body(ServerStatusDto.class); LOGGER.debug("Server health of {}: {}", serverUrl, status); return status; } public VersionStatusDto serverVersion(String serverUrl) { - return healthClient.get() + return checked(healthClient.get() .uri(serverUrl + Endpoints.SERVER_VERSION.getPath()) - .retrieve() + .retrieve()) .body(VersionStatusDto.class); } public List listBackups(String serverUrl) { - List backups = restClient.get() - .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) - .retrieve() + List backups = authed(restClient.get().uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()), serverUrl) .body(new ParameterizedTypeReference<>() {}); LOGGER.debug("Received {} backup(s) from {}", backups == null ? 0 : backups.size(), serverUrl); return backups == null ? List.of() : backups; @@ -113,9 +168,7 @@ public List listBackups(String serverUrl) { public void triggerBackup(String serverUrl) { LOGGER.info("Triggering backup on {}", serverUrl); try { - backupRunClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() + authed(backupRunClient.post().uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()), serverUrl) .toBodilessEntity(); } catch (ResourceAccessException e) { if (RequestTimeouts.isReadTimeout(e)) { @@ -124,24 +177,37 @@ public void triggerBackup(String serverUrl) { + " and is probably still running on the server. The dashboard's live status shows when it finishes.", e); } throw e; + } catch (RestClientResponseException e) { + if (e.getStatusCode().is5xxServerError()) { + throw new BackupRunFailedException(failureReason(e), e); + } + throw e; } LOGGER.info("Backup finished on {}", serverUrl); } + private static String failureReason(RestClientResponseException e) { + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + if (body != null && body.error() != null && !body.error().isBlank()) { + return body.error(); + } + } catch (RuntimeException ignored) { + } + return "MediaGarrd server responded with " + e.getStatusCode().value(); + } + public ServerStatusDto updateServerSchedule(String serverUrl, Duration interval) { LOGGER.info("Updating server schedule on {} to {}", serverUrl, interval); - return restClient.put() + return authed(restClient.put() .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(Map.of("backupInterval", interval.toString())) - .retrieve() + .body(Map.of("backupInterval", interval.toString())), serverUrl) .body(ServerStatusDto.class); } public ServerConfigDto serverConfig(String serverUrl) { - return restClient.get() - .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) - .retrieve() + return authed(restClient.get().uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()), serverUrl) .body(ServerConfigDto.class); } @@ -150,95 +216,261 @@ public ServerConfigDto updateServerConfig(String serverUrl, String backupLocatio Map body = new HashMap<>(); body.put("backupLocation", backupLocation); body.put("retentionCount", retentionCount); - return restClient.put() + return authed(restClient.put() .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(body) - .retrieve() + .body(body), serverUrl) .body(ServerConfigDto.class); } + public WebhookStatusDto webhook(String serverUrl) { + return authed(restClient.get().uri(serverUrl + Endpoints.SERVER_WEBHOOK.getPath()), serverUrl) + .body(WebhookStatusDto.class); + } + + public WebhookStatusDto updateWebhook(String serverUrl, String url) { + LOGGER.info("{} the failure webhook on {}", url == null || url.isBlank() ? "Clearing" : "Updating", serverUrl); + Map body = new HashMap<>(); + body.put("url", url); + return authed(restClient.put() + .uri(serverUrl + Endpoints.SERVER_WEBHOOK.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body), serverUrl) + .body(WebhookStatusDto.class); + } + + public WebhookTestDto testWebhook(String serverUrl) { + LOGGER.info("Sending a test message through the failure webhook on {}", serverUrl); + return authed(restClient.post().uri(serverUrl + Endpoints.SERVER_WEBHOOK_TEST.getPath()), serverUrl) + .body(WebhookTestDto.class); + } + public List listServices(String serverUrl) { - List services = restClient.get() - .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) - .retrieve() + List services = authed(restClient.get().uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()), serverUrl) .body(new ParameterizedTypeReference<>() {}); return services == null ? List.of() : services; } public ServiceDto addService(String serverUrl, ServiceDto service) { LOGGER.info("Adding service {} on {}", service.name(), serverUrl); - return restClient.post() + return authed(restClient.post() .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) .contentType(MediaType.APPLICATION_JSON) - .body(service) - .retrieve() + .body(service), serverUrl) .body(ServiceDto.class); } public ServiceDto updateService(String serverUrl, String name, ServiceDto service) { LOGGER.info("Updating service {} on {}", name, serverUrl); - return restClient.put() + return authed(restClient.put() .uri(serverUrl + SERVICE_PATH, name) .contentType(MediaType.APPLICATION_JSON) - .body(service) - .retrieve() + .body(service), serverUrl) .body(ServiceDto.class); } public void removeService(String serverUrl, String name) { LOGGER.info("Removing service {} from {}", name, serverUrl); - restClient.delete() - .uri(serverUrl + SERVICE_PATH, name) - .retrieve() + authed(restClient.delete().uri(serverUrl + SERVICE_PATH, name), serverUrl) + .toBodilessEntity(); + } + + public StoredPairing pair(String serverUrl, String credential, String name) { + LOGGER.info("Pairing with {}", serverUrl); + Map body = new HashMap<>(); + body.put("pin", credential); + if (name != null && !name.isBlank()) { + body.put("name", name); + } + PairReply reply; + try { + reply = redirectsRefused(restClient.post() + .uri(serverUrl + Endpoints.SERVER_PAIR.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body) + .retrieve()) + .body(PairReply.class); + } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == 401) { + throw new InvalidRequestException(serverMessage(e, "The PIN or pairing code was not accepted")); + } + throw e; + } + if (reply == null || reply.token() == null || reply.token().isBlank()) { + throw new UpstreamResponseException("The server did not return a token"); + } + return new StoredPairing(reply.token(), reply.id(), reply.name()); + } + + public void confirmPairing(String serverUrl, String token) { + LOGGER.info("Confirming the pairing with {}", serverUrl); + ConfirmReply reply; + try { + reply = redirectsRefused(healthClient.get() + .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .retrieve()) + .body(ConfirmReply.class); + } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == 401) { + throw new InvalidRequestException("The server did not accept this pairing. Enter the PIN or a pairing code again"); + } + int status = e.getStatusCode().value(); + String message = "The server could not confirm the pairing (status " + status + "). Try again"; + if (status == 502 || status == 503 || status == 504) { + throw new ConfirmationUnavailableException(message); + } + throw new UpstreamResponseException(message); + } + if (reply == null || reply.running() == null || reply.backupRetentionCount() == null) { + throw new ConfirmationRefusedException("The server did not confirm the pairing. Check that it is a current MediaGarrd Server and try again"); + } + } + + public PairingCodeDto createPairingCode(String serverUrl) { + return authed(restClient.post().uri(serverUrl + Endpoints.SERVER_PAIRING_CODES.getPath()), serverUrl) + .body(PairingCodeDto.class); + } + + public void revokeClient(String serverUrl, String clientId) { + LOGGER.info("Unpairing from {}", serverUrl); + authed(restClient.delete().uri(serverUrl + Endpoints.SERVER_CLIENTS.getPath() + "/{id}", clientId), serverUrl) .toBodilessEntity(); } + public void addTokenRejectedListener(Consumer listener) { + tokenRejectedListeners.add(listener); + } + + private RestClient.ResponseSpec authed(RestClient.RequestHeadersSpec request, String serverUrl) { + String token = requireToken(serverUrl); + return checked(request.header(HttpHeaders.AUTHORIZATION, "Bearer " + token).retrieve(), serverUrl); + } + + private RestClient.ResponseSpec checked(RestClient.ResponseSpec response, String serverUrl) { + return redirectsRefused(response).onStatus(status -> status.value() == 401, (request, reply) -> { + throw rejected(serverUrl); + }); + } + + private PairingRequiredException rejected(String serverUrl) { + for (Consumer listener : tokenRejectedListeners) { + try { + listener.accept(serverUrl); + } catch (RuntimeException e) { + LOGGER.warn("Token rejected listener failed: {}", e.getMessage()); + } + } + return rejected(); + } + + private static RestClient.ResponseSpec checked(RestClient.ResponseSpec response) { + return redirectsRefused(response).onStatus(status -> status.value() == 401, (request, reply) -> { + throw rejected(); + }); + } + + private static RestClient.ResponseSpec redirectsRefused(RestClient.ResponseSpec response) { + return response.onStatus(status -> status.is3xxRedirection(), (request, reply) -> { + throw new ServerRedirectException(reply.getStatusCode().value(), reply.getHeaders().getFirst(HttpHeaders.LOCATION)); + }); + } + + private String requireToken(String serverUrl) { + return tokens.tokenFor(serverUrl) + .orElseThrow(() -> new PairingRequiredException("This client is not paired with the server, pair it first")); + } + + private static PairingRequiredException rejected() { + return new PairingRequiredException("The server rejected this client's token, pair it again"); + } + + private static String serverMessage(RestClientResponseException e, String fallback) { + try { + Map body = e.getResponseBodyAs(Map.class); + Object message = body == null ? null : body.get("error"); + return message == null ? fallback : message.toString(); + } catch (RuntimeException ignored) { + return fallback; + } + } + public Path downloadById(String serverUrl, String backupId, Path destination, DownloadProgressListener progressListener) { URI uri = URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + UriUtils.encodePathSegment(backupId, StandardCharsets.UTF_8) + "/download"); LOGGER.info("Downloading backup {} from {} to {}", backupId, serverUrl, destination); Path temp = destination.resolveSibling(destination.getFileName() + ".part"); + String token = requireToken(serverUrl); try { - HttpResponse response = httpClient.send(HttpRequest.newBuilder(uri).GET().build(), HttpResponse.BodyHandlers.ofInputStream()); + HttpRequest request = HttpRequest.newBuilder(uri) + .timeout(REQUEST_TIMEOUT) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .GET() + .build(); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); try (InputStream body = response.body()) { + if (response.statusCode() == 401) { + throw rejected(serverUrl); + } + if (response.statusCode() / 100 == 3) { + throw new ServerRedirectException(response.statusCode(), response.headers().firstValue(HttpHeaders.LOCATION).orElse(null)); + } if (response.statusCode() / 100 != 2) { String snippet = new String(body.readNBytes(256), StandardCharsets.UTF_8); LOGGER.error("Download of backup {} failed with HTTP {}: {}", backupId, response.statusCode(), snippet); - throw new IllegalStateException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); + throw new DownloadFailedException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); } - Files.createDirectories(destination.getParent()); + OwnerOnlyFiles.createDirectories(destination.getParent()); long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); copy(body, temp, totalBytes, progressListener); } if (!looksLikeZip(temp)) { - throw new IllegalStateException("Server returned non-zip content for backup " + backupId); + throw new DownloadFailedException("Server returned non-zip content for backup " + backupId); } Files.move(temp, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); LOGGER.info("Downloaded backup {} to {} ({} bytes)", backupId, destination, Files.size(destination)); return destination; } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new IllegalStateException("Download of backup " + backupId + " was interrupted", e); + throw new DownloadFailedException("Download of backup " + backupId + " was interrupted", e); } catch (IOException e) { LOGGER.error("Failed to save backup {} to {}", backupId, destination, e); - throw new IllegalStateException("Failed to save backup " + backupId + ": " + e.getMessage(), e); + throw new DownloadFailedException("Failed to download backup " + backupId, e); } finally { - deleteQuietly(temp); + QuietFiles.delete(temp); } } - private static void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { - try (OutputStream out = Files.newOutputStream(target)) { + private void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { + AtomicLong lastRead = new AtomicLong(System.nanoTime()); + AtomicBoolean stalled = new AtomicBoolean(); + long checkMillis = Math.max(10, stallTimeout.toMillis() / 4); + ScheduledFuture guard = stallWatchdog.scheduleWithFixedDelay(() -> { + if (System.nanoTime() - lastRead.get() > stallTimeout.toNanos() && stalled.compareAndSet(false, true)) { + try { + in.close(); + } catch (IOException | RuntimeException ignored) { + } + } + }, checkMillis, checkMillis, TimeUnit.MILLISECONDS); + try (OutputStream out = OwnerOnlyFiles.newOutputStream(target)) { byte[] buffer = new byte[BUFFER_SIZE]; long written = 0; int read; while ((read = in.read(buffer)) != -1) { + lastRead.set(System.nanoTime()); out.write(buffer, 0, read); written += read; if (progressListener != null) { progressListener.onProgress(written, totalBytes); } } + } catch (IOException e) { + if (stalled.get()) { + throw new DownloadFailedException("The server stopped sending data for " + stallTimeout.toSeconds() + " seconds", e); + } + throw e; + } finally { + guard.cancel(false); } } @@ -253,11 +485,8 @@ private static boolean looksLikeZip(Path path) throws IOException { && ((header[2] == 3 && header[3] == 4) || (header[2] == 5 && header[3] == 6) || (header[2] == 7 && header[3] == 8)); } - private static void deleteQuietly(Path path) { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); - } + @PreDestroy + void shutdown() { + stallWatchdog.shutdownNow(); } } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java index 83b35db..1086fe9 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -1,6 +1,7 @@ package wellatleastitried.mediagarrdclient.service; import java.io.IOException; +import java.io.InputStream; import java.net.ConnectException; import java.net.Inet4Address; import java.net.InetAddress; @@ -40,12 +41,13 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.api.Endpoints; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; @Service public class ServerDiscoveryService { @@ -57,7 +59,9 @@ public class ServerDiscoveryService { private static final int MIN_SCAN_PREFIX_LENGTH = 24; private static final int FIRST_UNPRIVILEGED_PORT = 1024; private static final int MAX_PORT = 65535; + private static final int HTTPS_PORT = 443; private static final int MAX_CONCURRENT_PROBES = 256; + private static final int MAX_PROBE_BODY = 16 * 1024; 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); @@ -68,13 +72,22 @@ public class ServerDiscoveryService { enum Probe { OPEN, REFUSED, UNREACHABLE } - record Candidate(String host, InetAddress address, int port) { + record Candidate(String scheme, String host, InetAddress address, int port) { + Candidate(String host, InetAddress address, int port) { + this("http", host, address, port); + } + String url() { - return "http://" + (host.contains(":") ? "[" + host + "]" : host) + ":" + port; + String authority = host.contains(":") ? "[" + host + "]" : host; + boolean defaultPort = "https".equals(scheme) && port == HTTPS_PORT; + return scheme + "://" + authority + (defaultPort ? "" : ":" + port); } } - record HostInput(String host, Integer port) { + record HostInput(String scheme, String host, Integer port) { + boolean https() { + return "https".equals(scheme); + } } private record ProbeResult(Probe probe, String server) { @@ -83,24 +96,26 @@ private record ProbeResult(Probe probe, String server) { private record QuickResult(Optional server, boolean hostAlive) { } - private final Configuration configuration; + private final MediaGarrdProperties configuration; private final ClientStateService stateService; private final ObjectMapper mapper; - private final HttpClient httpClient = HttpClient.newBuilder() - .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) - .followRedirects(HttpClient.Redirect.NEVER) - .build(); + private final HttpClient httpClient; 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); + public ServerDiscoveryService(MediaGarrdProperties configuration, ClientStateService stateService, ObjectMapper mapper, ServerTls tls) { + this(configuration, stateService, mapper, tls, Executors.newVirtualThreadPerTaskExecutor(), PREFERRED_ATTEMPT_DEADLINE); } - ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper, ExecutorService executor, Duration preferredDeadline) { + ServerDiscoveryService(MediaGarrdProperties configuration, ClientStateService stateService, ObjectMapper mapper, ServerTls tls, ExecutorService executor, Duration preferredDeadline) { + this.httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); this.executor = executor; this.preferredDeadline = preferredDeadline; this.configuration = configuration; @@ -175,7 +190,24 @@ public Optional resolvePreferredServer() { } HostInput input = parseHost(preferred); InetAddress address = input == null ? null : resolve(input.host()); - return address == null ? Optional.empty() : quickResolve(input.host(), address, input.port(), deadline()).server(); + if (address == null) { + return Optional.empty(); + } + if (input.https()) { + return probeSecure(input, input.port()); + } + return quickResolve(input.host(), address, input.port(), deadline()).server(); + } + + private Optional probeSecure(HostInput input, Integer port) { + Candidate candidate = new Candidate("https", input.host(), null, port != null ? port : HTTPS_PORT); + boolean found = isMediaGarrdServer(candidate); + if (found) { + LOGGER.info("Resolved MediaGarrd server at {}", candidate.url()); + } else { + LOGGER.debug("No MediaGarrd server answered at {}", candidate.url()); + } + return found ? Optional.of(candidate.url()) : Optional.empty(); } public Optional resolveServerByIp(String input, Integer port) { @@ -186,6 +218,9 @@ public Optional resolveServerByIp(String input, Integer port) { return Optional.empty(); } Integer preferredPort = port != null ? port : parsed.port(); + if (parsed.https()) { + return probeSecure(parsed, preferredPort); + } long deadline = deadline(); QuickResult quick = quickResolve(parsed.host(), address, preferredPort, deadline); if (quick.server().isPresent() || !quick.hostAlive()) { @@ -257,22 +292,37 @@ private Probe connect(Candidate candidate, long deadline) { } boolean isMediaGarrdServer(Candidate candidate) { - HttpRequest request = HttpRequest.newBuilder(URI.create(candidate.url() + Endpoints.SERVER_HEALTH.getPath())) - .timeout(HEALTH_TIMEOUT) - .GET() - .build(); + return isMediaGarrdServer(candidate.url()); + } + + public boolean isMediaGarrdServer(String serverUrl) { + HttpRequest request; try { - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() != 200) { - return false; + request = HttpRequest.newBuilder(URI.create(serverUrl + Endpoints.SERVER_HEALTH.getPath())) + .timeout(HEALTH_TIMEOUT) + .GET() + .build(); + } catch (IllegalArgumentException e) { + return false; + } + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() != 200) { + return false; + } + byte[] bytes = body.readNBytes(MAX_PROBE_BODY + 1); + if (bytes.length > MAX_PROBE_BODY) { + return false; + } + JsonNode health = mapper.readTree(bytes); + return health.path("healthy").isBoolean() && health.has("backupInterval"); } - JsonNode health = mapper.readTree(response.body()); - return health.path("healthy").isBoolean() && health.has("backupInterval"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; - } catch (IOException | IllegalArgumentException e) { - LOGGER.debug("{} is not a MediaGarrd server: {}", candidate.url(), e.getMessage()); + } catch (IOException | IllegalArgumentException | JacksonException e) { + LOGGER.debug("{} is not a MediaGarrd server: {}", serverUrl, e.getMessage()); return false; } } @@ -332,7 +382,8 @@ static HostInput parseHost(String input) { return null; } String host = uri.getHost().startsWith("[") ? uri.getHost().substring(1, uri.getHost().length() - 1) : uri.getHost(); - return new HostInput(host, uri.getPort() > 0 ? uri.getPort() : null); + String scheme = "https".equalsIgnoreCase(uri.getScheme()) ? "https" : "http"; + return new HostInput(scheme, host, uri.getPort() > 0 ? uri.getPort() : null); } catch (IllegalArgumentException e) { return null; } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java index 02a0711..9e53c9f 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamService.java @@ -1,39 +1,40 @@ 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.Optional; 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.RejectedExecutionException; 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 java.util.function.LongSupplier; 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 tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import wellatleastitried.mediagarrdclient.api.Endpoints; +import wellatleastitried.mediagarrdclient.protocol.Endpoints; @Service public class ServerEventStreamService { @@ -51,24 +52,19 @@ public class ServerEventStreamService { 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 class Subscription 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 volatile boolean rejected; private boolean linkUp; private boolean eventsSeen; private Thread thread; - private Stream(String serverUrl) { + private Subscription(String serverUrl) { this.serverUrl = serverUrl; } @@ -110,39 +106,32 @@ private boolean pause(Duration delay) { @Override public void run() { - Duration backoff = timing.initialBackoff(); + ReconnectPolicy policy = new ReconnectPolicy(timing.initialBackoff(), timing.maxBackoff(), timing.unsupportedRetry(), timing.minStreamLifetime()); try { while (!isCancelled()) { - Outcome outcome; + ReconnectPolicy.Outcome outcome; long startedNanos = System.nanoTime(); try { outcome = connectAndRead(); } catch (RuntimeException e) { LOGGER.warn("Event stream of {} failed: {}", serverUrl, e.getMessage()); - outcome = Outcome.FAILED; + outcome = ReconnectPolicy.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) { + ReconnectPolicy.Decision decision = policy.next(outcome, eventsSeen, System.nanoTime() - startedNanos); + eventsSeen = false; + if (decision.outcome() == ReconnectPolicy.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 (decision.outcome() == ReconnectPolicy.Outcome.REJECTED) { + rejected = true; + reportRejected(); + break; } - if (pause(delay)) { + if (pause(decision.delay())) { break; } } @@ -151,93 +140,80 @@ public void run() { } } - private Outcome connectAndRead() { + private ReconnectPolicy.Outcome connectAndRead() { + Optional token = stateService.tokenFor(serverUrl); + if (token.isEmpty()) { + return ReconnectPolicy.Outcome.REJECTED; + } HttpRequest request = HttpRequest.newBuilder(URI.create(serverUrl + Endpoints.SERVER_EVENTS.getPath())) .timeout(timing.headerTimeout()) .header("Accept", "text/event-stream") + .header("Authorization", "Bearer " + token.get()) .GET() .build(); CompletableFuture> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()); pending = future; if (isCancelled()) { future.cancel(true); - return Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } HttpResponse response; try { response = future.get(); } catch (InterruptedException | CancellationException e) { - return Outcome.FAILED; + return ReconnectPolicy.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; + return ReconnectPolicy.Outcome.FAILED; } body = response.body(); if (isCancelled()) { closeBody(); - return Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } int status = response.statusCode(); + if (status == 401) { + closeBody(); + LOGGER.warn("{} rejected this client's token, the event stream stays closed until the client is paired again", serverUrl); + return ReconnectPolicy.Outcome.REJECTED; + } + if (status / 100 == 3) { + closeBody(); + LOGGER.warn("Event stream of {} was answered with a redirect to {}, the client does not follow redirects, use that address instead", + serverUrl, response.headers().firstValue("Location").orElse("an unknown location")); + return ReconnectPolicy.Outcome.FAILED; + } if (status == 404) { closeBody(); - LOGGER.info("{} has no event stream, falling back to polling and retrying in {}", serverUrl, timing.unsupportedRetry()); - return Outcome.UNSUPPORTED; + LOGGER.debug("{} has no event stream, falling back to polling and retrying in {}", serverUrl, timing.unsupportedRetry()); + return ReconnectPolicy.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 ReconnectPolicy.Outcome.FAILED; } return read(response.body()); } - private Outcome read(InputStream input) { + private ReconnectPolicy.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); - } + try { + boolean sawEvent = SseReader.read(input, () -> lastActivityNanos = System.nanoTime(), (name, data) -> { + if (!eventsSeen) { + eventsSeen = true; + reportLink(true); } - } - return sawEvent ? Outcome.ROLLOVER : Outcome.FAILED; + dispatch(name, data); + }); + return sawEvent ? ReconnectPolicy.Outcome.ROLLOVER : ReconnectPolicy.Outcome.FAILED; } catch (IOException | RuntimeException e) { if (!isCancelled()) { LOGGER.debug("Event stream of {} ended: {}", serverUrl, e.getMessage()); } - return Outcome.FAILED; + return ReconnectPolicy.Outcome.FAILED; } finally { watchdog.cancel(false); } @@ -270,6 +246,14 @@ private void reportLink(boolean connected) { } } + private void reportRejected() { + synchronized (lock) { + if (current == this) { + dashboard.pairingRejected(serverUrl); + } + } + } + private void dispatch(String name, String data) { if (!FORWARDED_EVENTS.contains(name)) { return; @@ -279,80 +263,145 @@ private void dispatch(String name, String data) { if (name.equals("state") && !node.has("running")) { return; } + String forwarded = mapper.writeValueAsString(node); 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 "backups-changed" -> dashboard.backupsChanged(serverUrl, forwarded); case "config-changed" -> dashboard.configChanged(serverUrl); - default -> dashboard.runEvent(serverUrl, name, data, running); + default -> dashboard.runEvent(serverUrl, name, forwarded, running); } } - } catch (IOException e) { + } catch (JacksonException 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 HttpClient httpClient; private final ThreadFactory threadFactory; private final ScheduledExecutorService scheduler; + private final LongSupplier nanoTime; private final Object lock = new Object(); - private Stream current; + private Subscription current; + private long lastRecoveryRestartNanos; + private boolean recoveryRestarted; + private ScheduledFuture deferredRecovery; @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)); + public ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls) { + this(stateService, dashboard, mapper, tls, new Timing(HEADER_TIMEOUT, WATCHDOG, INITIAL_BACKOFF, MAX_BACKOFF, UNSUPPORTED_RETRY, MIN_STREAM_LIFETIME)); + } + + ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls, Timing timing) { + this(stateService, dashboard, mapper, tls, timing, System::nanoTime, Executors.newSingleThreadScheduledExecutor( + runnable -> Thread.ofPlatform().daemon().name("server-event-watchdog").unstarted(runnable))); } - ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, Timing timing) { + ServerEventStreamService(ClientStateService stateService, DashboardService dashboard, ObjectMapper mapper, ServerTls tls, Timing timing, + LongSupplier nanoTime, ScheduledExecutorService scheduler) { + this.nanoTime = nanoTime; + this.httpClient = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NEVER) + .sslContext(tls.context()) + .build(); 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)); + this.scheduler = scheduler; } @PostConstruct void start() { stateService.addActiveServerListener(ignored -> reconcile()); + stateService.addPairingListener(this::pairingChanged); + dashboard.addRecoveryListener(this::recovered); reconcile(); } + void pairingChanged(String serverUrl) { + synchronized (lock) { + if (current != null && Objects.equals(current.serverUrl, serverUrl)) { + dropCurrent(); + } + reconcile(); + } + } + + void recovered(String serverUrl) { + synchronized (lock) { + if (current != null && Objects.equals(current.serverUrl, serverUrl)) { + recover(current); + } + } + } + + private void recover(Subscription stream) { + synchronized (lock) { + if (current != stream || !stream.rejected) { + return; + } + long now = nanoTime.getAsLong(); + if (recoveryRestarted && now - lastRecoveryRestartNanos < timing.unsupportedRetry().toNanos()) { + long remaining = timing.unsupportedRetry().toNanos() - (now - lastRecoveryRestartNanos); + cancelDeferredRecovery(); + try { + deferredRecovery = scheduler.schedule(() -> recover(stream), remaining, TimeUnit.NANOSECONDS); + } catch (RejectedExecutionException ignored) { + deferredRecovery = null; + } + return; + } + recoveryRestarted = true; + lastRecoveryRestartNanos = now; + dropCurrent(); + reconcile(); + } + } + + private void dropCurrent() { + cancelDeferredRecovery(); + if (current != null) { + current.cancel(); + current = null; + } + } + + private void cancelDeferredRecovery() { + if (deferredRecovery != null) { + deferredRecovery.cancel(false); + deferredRecovery = null; + } + } + void reconcile() { synchronized (lock) { - String target = normalize(stateService.getActiveServer()); + String active = ServerUrls.nullIfBlank(stateService.getActiveServer()); + String target = active != null && stateService.hasPairing(active) ? active : null; String running = current == null ? null : current.serverUrl; if (Objects.equals(target, running)) { return; } - if (current != null) { - current.cancel(); - current = null; - } + dropCurrent(); dashboard.sync(); if (target != null) { - Stream stream = new Stream(target); + Subscription stream = new Subscription(target); stream.thread = threadFactory.newThread(stream); current = stream; stream.thread.start(); - LOGGER.info("Subscribing to live events of {}", target); + LOGGER.debug("Subscribing to live events of {}", target); } } } @@ -360,16 +409,9 @@ void reconcile() { @PreDestroy void shutdown() { synchronized (lock) { - if (current != null) { - current.cancel(); - current = null; - } + dropCurrent(); } 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/ServerRedirectException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java new file mode 100644 index 0000000..ea94be7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerRedirectException.java @@ -0,0 +1,17 @@ +package wellatleastitried.mediagarrdclient.service; + +public class ServerRedirectException extends RuntimeException { + + private final String location; + + public ServerRedirectException(int status, String location) { + super("The server answered with a redirect (HTTP " + status + ")" + + (location == null || location.isBlank() ? "" : " to " + location) + + ". The client does not follow redirects, so use that address as the server address instead."); + this.location = location; + } + + public String location() { + return location; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java new file mode 100644 index 0000000..905f95d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerSelectionService.java @@ -0,0 +1,39 @@ +package wellatleastitried.mediagarrdclient.service; + +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; + +@Service +public class ServerSelectionService { + + private final ClientStateService stateService; + private final ServerDiscoveryService discoveryService; + + public ServerSelectionService(ClientStateService stateService, ServerDiscoveryService discoveryService) { + this.stateService = stateService; + this.discoveryService = discoveryService; + } + + public void select(ServerSelectionRequest request) { + if (StringUtils.hasText(request.serverUrl())) { + String serverUrl = ServerUrls.requireHttp(request.serverUrl()); + if (!stateService.isKnownServer(serverUrl) && !discoveryService.isMediaGarrdServer(serverUrl)) { + throw new InvalidRequestException("No MediaGarrd server found at " + serverUrl); + } + stateService.setActiveServer(serverUrl); + return; + } + if (!StringUtils.hasText(request.serverIp())) { + throw new InvalidRequestException("Either serverUrl or serverIp must be provided"); + } + Integer port = request.serverPort(); + if (port != null && (port < 1 || port > 65535)) { + throw new InvalidRequestException("serverPort must be between 1 and 65535"); + } + String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) + .orElseThrow(() -> new InvalidRequestException("No MediaGarrd server found at " + request.serverIp().trim())); + stateService.setActiveServer(resolved); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java new file mode 100644 index 0000000..6b85af7 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTls.java @@ -0,0 +1,175 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedTrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@Component +public class ServerTls { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerTls.class); + + private final SSLContext context; + + @Autowired + public ServerTls(MediaGarrdProperties configuration) { + this(configuration.getServerCa()); + } + + ServerTls(String caFile) { + this.context = caFile == null || caFile.isBlank() ? platformDefault() : withExtraAuthorities(Path.of(caFile.trim())); + } + + public static ServerTls defaults() { + return new ServerTls(""); + } + + public SSLContext context() { + return context; + } + + private static SSLContext platformDefault() { + try { + return SSLContext.getDefault(); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not load the default TLS configuration: " + e.getMessage(), e); + } + } + + private static SSLContext withExtraAuthorities(Path caFile) { + try { + X509ExtendedTrustManager extra = extraTrustManager(readCertificates(caFile)); + X509ExtendedTrustManager composite = new CompositeTrustManager(defaultTrustManager(), extra); + SSLContext created = SSLContext.getInstance("TLS"); + created.init(null, new TrustManager[] {composite}, null); + LOGGER.info("Trusting the certificate authorities in {} in addition to the default ones for MediaGarrd servers", caFile); + return created; + } catch (IOException | GeneralSecurityException e) { + throw new IllegalStateException("MEDIAGARRD_SERVER_CA " + caFile + " could not be used: " + e.getMessage(), e); + } + } + + private static Collection readCertificates(Path caFile) throws IOException, CertificateException { + try (InputStream in = Files.newInputStream(caFile)) { + Collection certificates = CertificateFactory.getInstance("X.509").generateCertificates(in); + if (certificates.isEmpty()) { + throw new CertificateException("the file contains no PEM certificates"); + } + return certificates; + } + } + + private static X509ExtendedTrustManager extraTrustManager(Collection certificates) throws IOException, GeneralSecurityException { + KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); + store.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + store.setCertificateEntry("mediagarrd-ca-" + index++, certificate); + } + return extended(store); + } + + private static X509ExtendedTrustManager defaultTrustManager() throws GeneralSecurityException { + return extended(null); + } + + private static X509ExtendedTrustManager extended(KeyStore store) throws GeneralSecurityException { + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(store); + for (TrustManager manager : factory.getTrustManagers()) { + if (manager instanceof X509ExtendedTrustManager extended) { + return extended; + } + } + throw new GeneralSecurityException("No X509ExtendedTrustManager available"); + } + + private static final class CompositeTrustManager extends X509ExtendedTrustManager { + + private final X509ExtendedTrustManager primary; + private final X509ExtendedTrustManager secondary; + + private CompositeTrustManager(X509ExtendedTrustManager primary, X509ExtendedTrustManager secondary) { + this.primary = primary; + this.secondary = secondary; + } + + @FunctionalInterface + private interface Check { + void run(X509ExtendedTrustManager manager) throws CertificateException; + } + + private static void either(X509ExtendedTrustManager first, X509ExtendedTrustManager second, Check check) throws CertificateException { + try { + check.run(first); + } catch (CertificateException e) { + try { + check.run(second); + } catch (CertificateException ignored) { + throw e; + } + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType, socket)); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType, engine)); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + either(primary, secondary, manager -> manager.checkServerTrusted(chain, authType)); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + throw new CertificateException("Client certificates are not used"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + X509Certificate[] first = primary.getAcceptedIssuers(); + X509Certificate[] second = secondary.getAcceptedIssuers(); + X509Certificate[] all = java.util.Arrays.copyOf(first, first.length + second.length); + System.arraycopy(second, 0, all, first.length, second.length); + return all; + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java new file mode 100644 index 0000000..43162f3 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerTokens.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.Optional; + +@FunctionalInterface +public interface ServerTokens { + + Optional tokenFor(String serverUrl); +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java new file mode 100644 index 0000000..75ecd6d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerUrls.java @@ -0,0 +1,55 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.net.URI; +import java.util.Locale; + +public final class ServerUrls { + + private ServerUrls() { + } + + public static String normalize(String url) { + if (url == null) { + return null; + } + String trimmed = url.trim(); + try { + URI uri = URI.create(trimmed); + String scheme = uri.getScheme() == null ? null : uri.getScheme().toLowerCase(Locale.ROOT); + String host = uri.getHost(); + if (scheme == null || host == null || host.isBlank()) { + return stripTrailingSlashes(trimmed); + } + int port = uri.getPort(); + boolean defaultPort = port < 0 || ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443); + String path = uri.getRawPath() == null ? "" : stripTrailingSlashes(uri.getRawPath()); + return scheme + "://" + host.toLowerCase(Locale.ROOT) + (defaultPort ? "" : ":" + port) + path; + } catch (IllegalArgumentException e) { + return stripTrailingSlashes(trimmed); + } + } + + public static String requireHttp(String serverUrl) { + String trimmed = stripTrailingSlashes(serverUrl.trim()); + try { + URI uri = URI.create(trimmed); + if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && uri.getHost() != null && !uri.getHost().isBlank()) { + return normalize(trimmed); + } + } catch (IllegalArgumentException ignored) { + } + throw new InvalidRequestException("serverUrl must be an http:// or https:// URL: " + serverUrl); + } + + public static String nullIfBlank(String url) { + return url == null || url.isBlank() ? null : url; + } + + private static String stripTrailingSlashes(String value) { + int end = value.length(); + while (end > 0 && value.charAt(end - 1) == '/') { + end--; + } + return value.substring(0, end); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java new file mode 100644 index 0000000..9c04a96 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServiceNames.java @@ -0,0 +1,18 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.util.regex.Pattern; + +public final class ServiceNames { + + private static final Pattern VALID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.-]{0,63}"); + + private ServiceNames() { + } + + public static String require(String name) { + if (name == null || !VALID.matcher(name).matches()) { + throw new InvalidRequestException("Service names use letters, digits, '.', '_' and '-', start with a letter or digit and have at most 64 characters"); + } + return name; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java new file mode 100644 index 0000000..618ee99 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SessionService.java @@ -0,0 +1,188 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class SessionService { + + private static final Logger LOGGER = LoggerFactory.getLogger(SessionService.class); + static final Duration IDLE_TIMEOUT = Duration.ofHours(12); + static final Duration ABSOLUTE_TIMEOUT = Duration.ofDays(7); + static final int MAX_SESSIONS = 100; + private static final int TOKEN_BYTES = 32; + + private static final class Session { + private final Instant createdAt; + private Instant lastSeen; + + private Session(Instant now) { + this.createdAt = now; + this.lastSeen = now; + } + } + + private final Clock clock; + private final Duration idleTimeout; + private final Duration absoluteTimeout; + private final int maxSessions; + private final SecureRandom random = new SecureRandom(); + private final Map sessions = new LinkedHashMap<>(); + private final List> endedListeners = new CopyOnWriteArrayList<>(); + + @Autowired + public SessionService() { + this(Clock.systemUTC(), IDLE_TIMEOUT, ABSOLUTE_TIMEOUT, MAX_SESSIONS); + } + + SessionService(Clock clock, Duration idleTimeout, Duration absoluteTimeout, int maxSessions) { + this.clock = clock; + this.idleTimeout = idleTimeout; + this.absoluteTimeout = absoluteTimeout; + this.maxSessions = maxSessions; + } + + public synchronized String create() { + Instant now = clock.instant(); + evictExpired(now); + while (sessions.size() >= maxSessions) { + Iterator oldest = sessions.keySet().iterator(); + oldest.next(); + oldest.remove(); + } + byte[] bytes = new byte[TOKEN_BYTES]; + random.nextBytes(bytes); + String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + sessions.put(key(token), new Session(now)); + return token; + } + + public boolean validate(String token) { + if (token == null || token.isEmpty() || token.length() > 128) { + return false; + } + String key = keyOf(token); + boolean valid; + boolean expired = false; + synchronized (this) { + Instant now = clock.instant(); + Session session = sessions.get(key); + if (session == null) { + return false; + } + expired = expired(session, now); + if (expired) { + sessions.remove(key); + } else { + session.lastSeen = now; + } + valid = !expired; + } + if (expired) { + notifyEnded(List.of(key)); + } + return valid; + } + + public boolean isActive(String key) { + if (key == null) { + return false; + } + boolean expired = false; + boolean active; + synchronized (this) { + Session session = sessions.get(key); + if (session == null) { + return false; + } + expired = expired(session, clock.instant()); + if (expired) { + sessions.remove(key); + } + active = !expired; + } + if (expired) { + notifyEnded(List.of(key)); + } + return active; + } + + public void invalidate(String token) { + if (token == null) { + return; + } + String key = keyOf(token); + boolean removed; + synchronized (this) { + removed = sessions.remove(key) != null; + } + if (removed) { + notifyEnded(List.of(key)); + } + } + + public void clear() { + List keys; + synchronized (this) { + keys = List.copyOf(sessions.keySet()); + sessions.clear(); + } + notifyEnded(keys); + } + + public void addEndedListener(Consumer listener) { + endedListeners.add(listener); + } + + private void notifyEnded(List keys) { + for (String key : keys) { + for (Consumer listener : endedListeners) { + try { + listener.accept(key); + } catch (RuntimeException e) { + LOGGER.warn("Session listener failed: {}", e.getMessage()); + } + } + } + } + + private void evictExpired(Instant now) { + sessions.values().removeIf(session -> expired(session, now)); + } + + private boolean expired(Session session, Instant now) { + return Duration.between(session.lastSeen, now).compareTo(idleTimeout) >= 0 + || Duration.between(session.createdAt, now).compareTo(absoluteTimeout) >= 0; + } + + public static String keyOf(String token) { + return token == null ? null : key(token); + } + + private static String key(String token) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java b/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java new file mode 100644 index 0000000..ed406e2 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/SseReader.java @@ -0,0 +1,88 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +final class SseReader { + + static final int MAX_LINE_CHARS = 1024 * 1024; + static final int MAX_EVENT_CHARS = 1024 * 1024; + + interface Handler { + + void onEvent(String name, String data); + } + + private SseReader() { + } + + static boolean read(InputStream input, Runnable onActivity, Handler handler) throws IOException { + return read(input, onActivity, handler, MAX_LINE_CHARS, MAX_EVENT_CHARS); + } + + static boolean read(InputStream input, Runnable onActivity, Handler handler, int maxLine, int maxEvent) throws IOException { + boolean dispatched = false; + String name = null; + StringBuilder data = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { + String line; + while ((line = readLine(reader, maxLine)) != null) { + onActivity.run(); + if (line.isEmpty()) { + if (data.length() > 0) { + dispatched = true; + handler.onEvent(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'); + } + if (data.length() + value.length() > maxEvent) { + throw new IOException("The event is larger than " + maxEvent + " characters"); + } + data.append(value); + } + } + } + } + return dispatched; + } + + private static String readLine(BufferedReader reader, int maxLine) throws IOException { + StringBuilder line = new StringBuilder(); + int c; + while ((c = reader.read()) != -1) { + if (c == '\n') { + return line.toString(); + } + if (c == '\r') { + reader.mark(1); + if (reader.read() != '\n') { + reader.reset(); + } + return line.toString(); + } + if (line.length() >= maxLine) { + throw new IOException("The line is longer than " + maxLine + " characters"); + } + line.append((char) c); + } + return line.length() == 0 ? null : line.toString(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java b/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java new file mode 100644 index 0000000..abff567 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/StoredPairing.java @@ -0,0 +1,9 @@ +package wellatleastitried.mediagarrdclient.service; + +public record StoredPairing(String token, String id, String name) { + + @Override + public String toString() { + return "StoredPairing[id=" + id + ", name=" + name + "]"; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java index f4a5f2d..bbe670b 100644 --- a/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpdateCheckService.java @@ -1,6 +1,7 @@ package wellatleastitried.mediagarrdclient.service; import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.util.List; @@ -24,11 +25,12 @@ import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClient; import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.util.UriUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; @@ -43,6 +45,7 @@ record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("ht 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); + private static final String GITHUB_PAGES = "https://github.com/"; static final Duration MIN_INTERVAL = Duration.ofHours(1); private final String currentVersion; @@ -54,11 +57,11 @@ record GithubRelease(@JsonProperty("tag_name") String tagName, @JsonProperty("ht private final List> listeners = new CopyOnWriteArrayList<>(); @Autowired - public UpdateCheckService(Configuration properties, ObjectProvider buildProperties) { + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { this(properties, versionOf(buildProperties), Clock.systemUTC()); } - UpdateCheckService(Configuration properties, String currentVersion, Clock clock) { + UpdateCheckService(MediaGarrdProperties 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); @@ -133,9 +136,9 @@ private VersionStatusDto fromRelease(GithubRelease release) { 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(); + String url = release.htmlUrl() != null && release.htmlUrl().startsWith(GITHUB_PAGES) + ? release.htmlUrl() + : GITHUB_PAGES + repository + "/releases/tag/" + UriUtils.encodePathSegment(release.tagName().strip(), StandardCharsets.UTF_8); return result(CheckState.OK, latest.get(), url, null); } diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java b/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java new file mode 100644 index 0000000..fc6807f --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/UpstreamResponseException.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdclient.service; + +public class UpstreamResponseException extends RuntimeException { + + public UpstreamResponseException(String message) { + super(message); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index aaa3289..e37934f 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,6 +2,9 @@ server: port: ${CLIENT_PORT:8081} spring: + jackson: + deserialization: + fail-on-null-for-primitives: false task: scheduling: pool: @@ -22,3 +25,6 @@ mediagarrd: 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} + server-ca: ${MEDIAGARRD_SERVER_CA:} + password: ${CLIENT_PASSWORD:} + reset-password: ${CLIENT_RESET_PASSWORD:false} diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css index f9d15f6..839bfd1 100644 --- a/src/main/resources/static/css/mediagarrd.css +++ b/src/main/resources/static/css/mediagarrd.css @@ -3,7 +3,7 @@ --surface: #0a0a0a; --surface-raised: #111; --ink: #f5f5f5; - --muted: #737373; + --muted: #8a8a8a; --subtle: #404040; --border: #1f1f1f; --border-mid: #2e2e2e; @@ -63,7 +63,9 @@ body { color: var(--muted); background: var(--surface-raised); white-space: nowrap; + max-width: 22rem; } +.conn-badge [data-label] { overflow: hidden; text-overflow: ellipsis; } .conn-badge .dot { width: 7px; height: 7px; @@ -76,21 +78,24 @@ body { .conn-badge.ok .dot { background: var(--ok); box-shadow: 0 0 6px var(--ok); } .conn-badge.down { color: #fca5a5; border-color: #3b1111; } .conn-badge.down .dot { background: var(--warn); box-shadow: 0 0 6px var(--warn); } +.conn-badge.degraded { color: #fcd34d; border-color: #4a3510; } +.conn-badge.degraded .dot { background: #f59e0b; box-shadow: 0 0 6px #f59e0b; } .conn-badge.checking { color: var(--accent-dim); } .conn-badge.checking .dot { background: #a3a3a3; } .page { max-width: 1200px; margin: 0 auto; padding: 1.5rem; animation: fadein 350ms ease; } .workspace { display: grid; - grid-template-columns: 360px 1fr; + grid-template-columns: 360px minmax(0, 1fr); gap: 1rem; align-items: start; } -@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } +.workspace > * { min-width: 0; } +.stack { display: flex; flex-direction: column; gap: 1rem; } +@media (max-width: 900px) { .workspace { grid-template-columns: minmax(0, 1fr); } } .panel { background: var(--surface); border: 1px solid var(--border); } .panel.wide { grid-column: 1 / -1; } -.stack { display: flex; flex-direction: column; gap: 1rem; } .panel-header { display: flex; align-items: center; @@ -112,24 +117,29 @@ body { .field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } .field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } -.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } -.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } -.input-row-2 { display: grid; grid-template-columns: 1fr 110px; gap: 0.5rem; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; overflow-wrap: anywhere; } +.note + .field-group { margin-top: 0.75rem; } +.input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.5rem; } +.input-row-2 { display: grid; grid-template-columns: minmax(0, 1fr) 110px; gap: 0.5rem; } .button-row { display: flex; gap: 0.5rem; flex-wrap: wrap; } .button-row > button { flex: 1; } input, select { width: 100%; + min-width: 0; background: var(--bg); color: var(--ink); border: 1px solid var(--border-mid); padding: 0.5rem 0.65rem; font: inherit; font-size: 0.85rem; - outline: none; transition: border-color 150ms; } input:focus, select:focus { border-color: var(--subtle); } +input:focus-visible, select:focus-visible, button:focus-visible, a:focus-visible { + outline: 2px solid var(--ink); + outline-offset: 2px; +} input::placeholder { color: var(--muted); } button { @@ -148,7 +158,20 @@ button { } button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } button:active, button.clicked { transform: translateY(1px) scale(0.98); box-shadow: inset 0 0 0 2px #000; } -button:disabled { cursor: not-allowed; opacity: 0.62; transform: none; } +button:disabled, +button:disabled:hover, +button.ghost:disabled, +button.ghost:disabled:hover, +button.danger:disabled, +button.danger:disabled:hover { + cursor: not-allowed; + opacity: 0.45; + transform: none; + box-shadow: none; + background: transparent; + color: var(--muted); + border-color: var(--border-mid); +} button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } @@ -197,8 +220,8 @@ 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-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; padding: 1rem; } +@media (max-width: 900px) { .version-list { grid-template-columns: minmax(0, 1fr); } } .version-row { display: flex; flex-wrap: wrap; @@ -252,6 +275,7 @@ button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } margin-bottom: 0.75rem; } +.table-scroll { overflow-x: auto; } table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } thead th { padding: 0.5rem 0.75rem; @@ -264,6 +288,17 @@ thead th { border-bottom: 1px solid var(--border-mid); } thead th.sortable { cursor: pointer; user-select: none; transition: color 120ms; white-space: nowrap; } +thead th .sort-btn { + background: transparent; + border: none; + padding: 0; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-transform: inherit; + cursor: pointer; +} +thead th .sort-btn:hover { background: transparent; } thead th.sortable:hover, thead th.sortable.active { color: var(--accent-dim); } .sort-indicator { margin-left: 0.25rem; font-size: 0.65rem; color: var(--subtle); vertical-align: middle; } thead th.sortable.active .sort-indicator { color: var(--accent-dim); } @@ -279,8 +314,8 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } .empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } .icon-btn { - min-width: 34px; - height: 28px; + min-width: 44px; + height: 36px; padding: 0; font-size: 0.95rem; line-height: 1; @@ -314,6 +349,8 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } color: #fca5a5; } .banner.visible { display: block; } +.banner { scroll-margin-top: 5rem; } +.banner.warn { background: #1c1306; border-color: #4a3510; color: #fcd34d; } .banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } @keyframes sweep { @@ -325,3 +362,48 @@ tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } + +.topbar-end { display: flex; align-items: center; gap: 0.6rem; } + +.auth { + position: fixed; + inset: 0; + z-index: 20; + display: flex; + align-items: center; + justify-content: center; + padding: 1rem; + background: var(--bg); +} +.auth-card { width: min(380px, 100%); } +.auth-error { padding: 0 1rem 1rem; font-size: 0.8rem; color: #fca5a5; } +.auth-error:empty { display: none; } + +.code-box { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + margin-top: 0.75rem; + padding: 0.6rem 0.75rem; + border: 1px solid var(--border-mid); + background: var(--bg); +} +.code-box .code { font-family: var(--mono); font-size: 1.05rem; letter-spacing: 0.08em; user-select: all; } + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 621da1e..082b5e7 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -17,14 +17,43 @@ -
- - Connecting… +
+
+ + Connecting… +
+
+ +
- +
@@ -34,7 +63,7 @@
- +
@@ -80,6 +109,29 @@
+ +
@@ -98,7 +150,7 @@
- +
@@ -109,18 +161,20 @@ Backup Archives
+
- - - - - + + + + +
File Size Created ID GetGet
+

No backups loaded. Connect to a server to view archives.

@@ -153,7 +207,7 @@
-
+
- +
- +
-
-
Add Service
-
-
- - -
-
- Host paths to back up -
- -
-
- - -
-
+
+
+
Add Service
+
+
+ + +
+
+ Host paths to back up +
+ +
+
+ + +
+
+ + - +

No services configured yet.

+
- - -
Configured Services
- - - -
NamePaths
-

No services configured yet.

-
+
+
Failure Notifications
+
+
+ + +

The server sends a message when a backup fails or only partly succeeds, so you hear about it before the next scheduled try. Works with Discord, Slack and any receiver that accepts JSON. The saved address is never shown again.

+

Checking…

+
+
+ + + +
+
+
+
- + diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js index 83933a1..b62c675 100644 --- a/src/main/resources/static/js/api.js +++ b/src/main/resources/static/js/api.js @@ -1,12 +1,67 @@ +let loginRequiredHandler = () => {}; +let pairingRequiredHandler = () => {}; + +export function onLoginRequired(handler) { + loginRequiredHandler = handler; +} + +export function onPairingRequired(handler) { + pairingRequiredHandler = handler; +} + +export function loginRequired() { + loginRequiredHandler(); +} + +export function retryAfterSeconds(value, now = Date.now()) { + if (value === null || value === undefined || String(value).trim() === '') return null; + const text = String(value).trim(); + if (/^\d+$/.test(text)) return Number(text); + const date = Date.parse(text); + return Number.isFinite(date) ? Math.max(0, Math.ceil((date - now) / 1000)) : null; +} + +export function errorMessage(data, fallback) { + const body = data && typeof data === 'object' ? data : {}; + for (const candidate of [body.message, body.error]) { + if (typeof candidate === 'string' && candidate.trim()) return candidate; + } + return fallback; +} + +export function fallbackMessage(status) { + if (status === 502 || status === 504) return 'The client or a proxy in front of it did not respond in time.'; + return `The client answered with an error (${status}).`; +} + +export function toApiError({ status, data, retryAfter }) { + const error = new Error(errorMessage(data, fallbackMessage(status))); + error.status = status; + error.pairing = data?.pairing; + error.retryAfter = retryAfterSeconds(retryAfter); + return error; +} + async function request(method, url, body) { const response = await fetch(url, { method, - headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + headers: body === undefined + ? { 'X-MediaGarrd-Request': '1' } + : { 'Content-Type': 'application/json', 'X-MediaGarrd-Request': '1' }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!response.ok) { const data = await response.json().catch(() => ({})); - throw new Error(data.error || data.message || `${method} ${url} failed (${response.status})`); + if (response.status === 401 && data?.login === 'required') loginRequiredHandler(); + const error = toApiError({ + method, + url, + status: response.status, + data, + retryAfter: response.headers?.get('Retry-After'), + }); + if (error.pairing === 'required') pairingRequiredHandler(); + throw error; } const text = await response.text(); return text ? JSON.parse(text) : null; @@ -15,6 +70,13 @@ async function request(method, url, body) { const encode = encodeURIComponent; export const api = { + authStatus: () => request('GET', '/api/auth/status'), + login: (password) => request('POST', '/api/auth/login', { password }), + setPassword: (password) => request('POST', '/api/auth/set-password', { password }), + logout: () => request('POST', '/api/auth/logout'), + pair: (pin) => request('POST', '/api/client/pairing', { pin }), + createPairingCode: () => request('POST', '/api/client/pairing/code'), + unpair: () => request('DELETE', '/api/client/pairing'), status: () => request('GET', '/api/client/status'), discover: () => request('POST', '/api/client/discover'), dashboard: () => request('GET', '/api/client/dashboard'), @@ -27,6 +89,9 @@ export const api = { updatePickupInterval: (interval) => request('PUT', '/api/client/pickup-interval', { interval }), serverConfig: () => request('GET', '/api/client/server-config'), updateServerConfig: (config) => request('PUT', '/api/client/server-config', config), + webhook: () => request('GET', '/api/client/notifications/webhook'), + updateWebhook: (url) => request('PUT', '/api/client/notifications/webhook', { url }), + testWebhook: () => request('POST', '/api/client/notifications/webhook/test'), listServices: () => request('GET', '/api/client/services'), addService: (service) => request('POST', '/api/client/services', service), updateService: (name, service) => request('PUT', `/api/client/services/${encode(name)}`, service), diff --git a/src/main/resources/static/js/auth-model.js b/src/main/resources/static/js/auth-model.js new file mode 100644 index 0000000..cf347cb --- /dev/null +++ b/src/main/resources/static/js/auth-model.js @@ -0,0 +1,17 @@ +export const MIN_PASSWORD_LENGTH = 8; + +export function authScreen(status) { + if (!status) return 'loading'; + if (status.authenticated) return 'none'; + return status.passwordSet ? 'login' : 'set-password'; +} + +export function passwordProblem(password, confirm) { + if (password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`; + if (password !== confirm) return 'The passwords do not match.'; + return null; +} + +export function lockoutMessage(seconds) { + return seconds > 0 ? `Too many login attempts. Try again in ${seconds} second${seconds === 1 ? '' : 's'}.` : null; +} diff --git a/src/main/resources/static/js/auth.js b/src/main/resources/static/js/auth.js new file mode 100644 index 0000000..b836444 --- /dev/null +++ b/src/main/resources/static/js/auth.js @@ -0,0 +1,151 @@ +import { api, onLoginRequired } from './api.js'; +import { authScreen, lockoutMessage, passwordProblem } from './auth-model.js'; + +const RETRY_MIN_MS = 1000; +const RETRY_MAX_MS = 10000; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +export function initAuth({ root, logoutButton, background = [] }) { + const loginForm = root.querySelector('[data-login-form]'); + const setForm = root.querySelector('[data-set-form]'); + const title = root.querySelector('[data-auth-title]'); + const error = root.querySelector('[data-auth-error]'); + let reloading = false; + let lockout = null; + + function reload() { + if (reloading) return; + reloading = true; + location.reload(); + } + + function clearLockout() { + clearInterval(lockout); + lockout = null; + } + + function show(screen) { + clearLockout(); + root.hidden = screen === 'none'; + background.forEach((element) => { element.inert = screen !== 'none'; }); + loginForm.hidden = screen !== 'login'; + setForm.hidden = screen !== 'set-password'; + title.textContent = screen === 'set-password' ? 'Set a password' : 'Sign in'; + error.textContent = ''; + loginForm.querySelector('button').disabled = false; + setForm.querySelector('button').disabled = false; + if (screen !== 'none') (screen === 'login' ? loginForm : setForm).elements.password.focus(); + } + + function holdUntil(form, seconds) { + const button = form.querySelector('button'); + const until = Date.now() + seconds * 1000; + button.disabled = true; + clearLockout(); + const tick = () => { + const remaining = Math.ceil((until - Date.now()) / 1000); + if (remaining <= 0) { + clearLockout(); + error.textContent = ''; + button.disabled = false; + form.elements.password.focus(); + return; + } + error.textContent = lockoutMessage(remaining); + }; + tick(); + lockout = setInterval(tick, 1000); + } + + async function submit(form, action) { + const button = form.querySelector('button'); + const refocus = document.activeElement === button; + error.textContent = ''; + button.disabled = true; + try { + await action(); + reload(); + } catch (failure) { + error.textContent = failure.message; + if (failure.status === 429 && failure.retryAfter > 0) { + holdUntil(form, failure.retryAfter); + return; + } + if (failure.status === 409) { + await current().catch(() => {}); + error.textContent = failure.message; + return; + } + button.disabled = false; + if (refocus) form.elements.password.focus(); + } + } + + async function current() { + const screen = authScreen(await api.authStatus()); + if (screen === 'none') { + reload(); + return screen; + } + show(screen); + logoutButton.hidden = true; + return screen; + } + + loginForm.addEventListener('submit', (event) => { + event.preventDefault(); + submit(loginForm, () => api.login(loginForm.elements.password.value)); + }); + + setForm.addEventListener('submit', (event) => { + event.preventDefault(); + const { password, confirm } = setForm.elements; + const problem = passwordProblem(password.value, confirm.value); + if (problem) { + error.textContent = problem; + return; + } + submit(setForm, () => api.setPassword(password.value)); + }); + + logoutButton.addEventListener('click', async () => { + try { + await api.logout(); + } finally { + reload(); + } + }); + + onLoginRequired(reload); + + function showConnecting(message) { + root.hidden = false; + background.forEach((element) => { element.inert = true; }); + loginForm.hidden = true; + setForm.hidden = true; + title.textContent = 'MediaGarrd Client'; + error.textContent = message; + } + + return { + async ensureSignedIn() { + let delay = RETRY_MIN_MS; + for (;;) { + let screen = 'loading'; + try { + screen = authScreen(await api.authStatus()); + } catch (failure) { + showConnecting(`Client unreachable: ${failure.message}. Retrying…`); + } + if (screen !== 'loading') { + show(screen); + logoutButton.hidden = screen !== 'none'; + return screen === 'none'; + } + if (!error.textContent) showConnecting('Connecting…'); + await wait(delay); + delay = Math.min(delay * 2, RETRY_MAX_MS); + } + }, + }; +} diff --git a/src/main/resources/static/js/backups.js b/src/main/resources/static/js/backups.js index 19eee41..7384650 100644 --- a/src/main/resources/static/js/backups.js +++ b/src/main/resources/static/js/backups.js @@ -1,7 +1,12 @@ import { api } from './api.js'; import { bytes, percent, relativeTime } from './format.js'; +import { listingError } from './view-model.js'; const POLL_INTERVAL_MS = 350; +const POLL_MAX_INTERVAL_MS = 1500; +const EMPTY_DEFAULT = 'No backup archives found on server.'; +const EMPTY_DISCONNECTED = 'No backups loaded. Connect to a server to view archives.'; +const EMPTY_UNPAIRED = 'No backups loaded. Pair this client with the server to view archives.'; export function initBackups({ root, actions }, notify) { const rows = root.querySelector('tbody'); @@ -16,17 +21,22 @@ export function initBackups({ root, actions }, notify) { let backups = []; let serverRunning = false; let runInFlight = false; + let available = false; let latestTask = null; let pollTimer = null; + let pollDelay = POLL_INTERVAL_MS; let latestRequest = 0; + let generation = 0; + let pairingNeeded = false; + let emptyMessage = EMPTY_DISCONNECTED; function renderActions() { const backupBusy = serverRunning || runInFlight; - runButton.disabled = backupBusy; + runButton.disabled = backupBusy || !available; runButton.classList.toggle('busy', backupBusy); runButton.querySelector('.btn-label').textContent = backupBusy ? 'Backup In Progress' : 'Run Backup Now'; - pickupButton.disabled = Boolean(latestTask); + pickupButton.disabled = Boolean(latestTask) || !available; pickupButton.classList.toggle('busy', Boolean(latestTask)); pickupButton.querySelector('.btn-label').textContent = latestTask ? 'Downloading...' : 'Download Latest'; pickupButton.querySelector('.btn-progress-fill').style.width = @@ -37,7 +47,7 @@ export function initBackups({ root, actions }, notify) { const button = rowButtons.get(id); if (!button) return; const task = rowTasks.get(id); - button.disabled = Boolean(task); + button.disabled = Boolean(task) || !available; if (!task) { button.textContent = '↓'; return; @@ -70,10 +80,12 @@ export function initBackups({ root, actions }, notify) { return row; } - function renderTable(emptyMessage = 'No backup archives found on server.') { + function renderTable(message = emptyMessage) { + emptyMessage = message; headers.forEach((header) => { const active = header.dataset.sortKey === sort.key; header.classList.toggle('active', active); + header.setAttribute('aria-sort', active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'); header.querySelector('.sort-indicator').textContent = active ? (sort.dir === 'asc' ? '▲' : '▼') : '↕'; }); rowButtons.clear(); @@ -88,11 +100,11 @@ export function initBackups({ root, actions }, notify) { const loaded = await api.listBackups() || []; if (request !== latestRequest) return; backups = loaded; - renderTable(); + renderTable(EMPTY_DEFAULT); } catch (error) { if (request !== latestRequest) return; backups = []; - renderTable(`${error.message}. Connect to a server to view archives.`); + renderTable(listingError(error, available)); } } @@ -108,56 +120,80 @@ export function initBackups({ root, actions }, notify) { } async function poll() { - const tasks = [...rowTasks].map(([id, task]) => ({ id, task })); + const tasks = [...rowTasks].filter(([, task]) => task.taskId).map(([id, task]) => ({ id, task })); if (latestTask?.taskId) tasks.push({ id: null, task: latestTask }); if (!tasks.length) { pollTimer = null; return; } + const mine = generation; await Promise.all(tasks.map(async ({ id, task }) => { try { const progress = await api.pickupProgress(task.taskId); + if (mine !== generation) return; task.bytesWritten = progress.bytesWritten || 0; task.totalBytes = progress.totalBytes || task.totalBytes; if (progress.status === 'FAILED') notify.error(progress.error || 'Download failed'); if (progress.status === 'COMPLETED' || progress.status === 'FAILED') finish(id); } catch (error) { + if (mine !== generation) return; notify.error(error); finish(id); } })); + if (mine !== generation) { + pollTimer = null; + return; + } rowTasks.forEach((_, id) => renderRowButton(id)); renderActions(); - pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + pollDelay = Math.min(Math.round(pollDelay * 1.3), POLL_MAX_INTERVAL_MS); + pollTimer = setTimeout(poll, pollDelay); } function startPolling() { - if (!pollTimer) pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + if (pollTimer) return; + pollDelay = POLL_INTERVAL_MS; + pollTimer = setTimeout(poll, pollDelay); } - const toTask = (started) => ({ taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }); + function toTask(started) { + if (!started?.taskId) throw new Error('The client did not start a download.'); + return { taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }; + } async function pickupById(id) { - if (rowTasks.has(id)) return; + if (rowTasks.has(id) || !available) return; notify.clear(); + const mine = generation; + rowTasks.set(id, { taskId: null, bytesWritten: 0, totalBytes: 0 }); + renderRowButton(id); try { - rowTasks.set(id, toTask(await api.pickupById(id))); - renderRowButton(id); + const task = toTask(await api.pickupById(id)); + if (mine !== generation) return; + rowTasks.set(id, task); startPolling(); } catch (error) { + if (mine !== generation) return; + rowTasks.delete(id); notify.error(error); } + renderRowButton(id); } pickupButton.addEventListener('click', async () => { - if (latestTask) return; + if (latestTask || !available) return; notify.clear(); + const mine = generation; latestTask = { taskId: null, bytesWritten: 0, totalBytes: 0 }; renderActions(); try { - latestTask = toTask(await api.pickupLatest()); + const task = toTask(await api.pickupLatest()); + if (mine !== generation) return; + latestTask = task; startPolling(); } catch (error) { + if (mine !== generation) return; latestTask = null; notify.error(error); } @@ -165,7 +201,7 @@ export function initBackups({ root, actions }, notify) { }); runButton.addEventListener('click', async () => { - if (serverRunning || runInFlight) return; + if (serverRunning || runInFlight || !available) return; notify.clear(); runInFlight = true; renderActions(); @@ -179,7 +215,7 @@ export function initBackups({ root, actions }, notify) { } }); - headers.forEach((header) => header.addEventListener('click', () => { + headers.forEach((header) => header.querySelector('button').addEventListener('click', () => { const key = header.dataset.sortKey; if (sort.key === key) { sort.dir = sort.dir === 'asc' ? 'desc' : 'asc'; @@ -195,16 +231,38 @@ export function initBackups({ root, actions }, notify) { refresh(); }); - renderTable('No backups loaded. Connect to a server to view archives.'); + renderTable(EMPTY_DISCONNECTED); renderActions(); + function clear() { + latestRequest++; + backups = []; + renderTable(pairingNeeded ? EMPTY_UNPAIRED : EMPTY_DISCONNECTED); + } + return { refresh, rerender: () => renderTable(), - clear() { - latestRequest++; - backups = []; - renderTable('No backups loaded. Connect to a server to view archives.'); + clear, + reset() { + generation++; + rowTasks.clear(); + latestTask = null; + clearTimeout(pollTimer); + pollTimer = null; + clear(); + renderActions(); + }, + setPairingNeeded(value) { + if (pairingNeeded === value) return; + pairingNeeded = value; + if (!available && backups.length === 0) renderTable(value ? EMPTY_UNPAIRED : EMPTY_DISCONNECTED); + }, + setAvailable(value) { + if (available === value) return; + available = value; + rowButtons.forEach((_, id) => renderRowButton(id)); + renderActions(); }, setServerRunning(running) { serverRunning = running; diff --git a/src/main/resources/static/js/busy.js b/src/main/resources/static/js/busy.js new file mode 100644 index 0000000..155f1b1 --- /dev/null +++ b/src/main/resources/static/js/busy.js @@ -0,0 +1,11 @@ +export async function withBusy(button, task) { + if (button.disabled) return undefined; + const refocus = document.activeElement === button; + button.disabled = true; + try { + return await task(); + } finally { + button.disabled = false; + if (refocus) button.focus(); + } +} diff --git a/src/main/resources/static/js/connection.js b/src/main/resources/static/js/connection.js index 47a8896..19456cf 100644 --- a/src/main/resources/static/js/connection.js +++ b/src/main/resources/static/js/connection.js @@ -62,6 +62,7 @@ export function initConnection({ root, statusPanel, badge }, notify, { resync }) if (busy) return null; notify.clear(); busy = true; + const focused = root.contains(document.activeElement) ? document.activeElement : null; setBadge('checking', label); scanBar.classList.add('active'); controls.forEach((control) => { control.disabled = true; }); @@ -74,6 +75,7 @@ export function initConnection({ root, statusPanel, badge }, notify, { resync }) busy = false; scanBar.classList.remove('active'); controls.forEach((control) => { control.disabled = false; }); + if (focused) focused.focus(); if (latest) render(latest); await resync(); return result; diff --git a/src/main/resources/static/js/dashboard-model.js b/src/main/resources/static/js/dashboard-model.js index 15fbf25..37dfa0c 100644 --- a/src/main/resources/static/js/dashboard-model.js +++ b/src/main/resources/static/js/dashboard-model.js @@ -2,8 +2,12 @@ function reachableLink(link) { return link === 'LIVE' || link === 'DEGRADED'; } +export function needsPairing(state) { + return state.activeServer !== null && (state.pairing === 'REQUIRED' || state.pairing === 'REJECTED'); +} + export function canLoadBackups(state) { - return state.loaded && state.clientReachable && state.activeServer !== null && reachableLink(state.link); + return state.loaded && state.clientReachable && state.activeServer !== null && reachableLink(state.link) && !needsPairing(state); } export function emptyState() { @@ -16,6 +20,7 @@ export function emptyState() { running: null, health: null, versions: null, + pairing: 'NONE', }; } @@ -29,6 +34,7 @@ function fromSnapshot(payload) { running: payload.running ?? null, health: payload.health || null, versions: payload.versions || null, + pairing: payload.pairing || 'PAIRED', }; } @@ -57,6 +63,8 @@ export function reduce(state, name, payload) { return { ...base, health: { backupInterval: payload.backupInterval, backupRetentionCount: payload.backupRetentionCount } }; case 'versions': return { ...base, versions: payload }; + case 'pairing': + return { ...base, pairing: payload.state || 'PAIRED' }; default: return base; } @@ -71,6 +79,7 @@ export function changes(prev, next, eventName) { const reachedAgain = !first && ( (!reachableLink(prev.link) && reachableLink(next.link)) || (!prev.clientReachable && next.clientReachable) + || (needsPairing(prev) && !needsPairing(next)) ); const finished = prev.running === true && next.running === false; const announced = eventName === 'backups-changed' || eventName === 'run-finished'; diff --git a/src/main/resources/static/js/events.js b/src/main/resources/static/js/events.js index 566bccf..743ba7e 100644 --- a/src/main/resources/static/js/events.js +++ b/src/main/resources/static/js/events.js @@ -1,18 +1,19 @@ 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']; +export const EVENT_NAMES = ['snapshot', 'link', 'state', 'run-started', 'run-finished', 'servers', 'config', 'backups-changed', 'versions', 'pairing', '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 }) { +export function initEvents({ onEvent, onConnection, checkSession = async () => {} }) { let source = null; let retryTimer = null; let retryDelay = RETRY_MIN_MS; let lastMessageAt = 0; + let opened = false; const reachability = createReachability({ graceMs: RECONNECT_GRACE_MS, onChange: onConnection }); function parse(event) { @@ -45,7 +46,9 @@ export function initEvents({ onEvent, onConnection }) { const created = new EventSource(EVENTS_URL); source = created; lastMessageAt = Date.now(); + opened = false; created.addEventListener('open', () => { + opened = true; lastMessageAt = Date.now(); retryDelay = RETRY_MIN_MS; reachability.alive(); @@ -54,8 +57,13 @@ export function initEvents({ onEvent, onConnection }) { if (source !== created) return; const closed = created.readyState === EventSource.CLOSED; reachability.failed(closed); - if (!closed) return; + if (!closed) { + opened = false; + return; + } + const neverOpened = !opened; close(); + if (neverOpened) checkSession().catch(() => {}); scheduleReopen(); }); EVENT_NAMES.forEach((name) => created.addEventListener(name, (event) => { @@ -81,11 +89,10 @@ export function initEvents({ onEvent, onConnection }) { setInterval(() => { if (source && Date.now() - lastMessageAt > SILENCE_LIMIT_MS) { close(); + reachability.failed(true); open(); } }, SILENCE_CHECK_MS); open(); - - return { open, close }; } diff --git a/src/main/resources/static/js/format.js b/src/main/resources/static/js/format.js index 68a82b6..4f38ece 100644 --- a/src/main/resources/static/js/format.js +++ b/src/main/resources/static/js/format.js @@ -6,7 +6,30 @@ export function seconds(duration) { return Number(hours) * 3600 + Number(minutes) * 60 + Number(secs); } -export const toDuration = (minutes) => `PT${Math.round(minutes)}M`; +export function toDuration(minutes) { + const total = Math.round(minutes * 60); + return total % 60 === 0 ? `PT${total / 60}M` : `PT${total}S`; +} + +export const MIN_INTERVAL_SECONDS = 900; +export const MAX_INTERVAL_SECONDS = 31536000; +export const INTERVAL_MESSAGE = 'Backup interval must be between 15 minutes and 365 days'; + +export function intervalProblem(hours) { + const total = Math.round(hours * 3600); + const valid = Number.isFinite(total) && total >= MIN_INTERVAL_SECONDS && total <= MAX_INTERVAL_SECONDS; + return valid ? null : INTERVAL_MESSAGE; +} + +export const MAX_PICKUP_MINUTES = 525600; +export const PICKUP_MESSAGE = 'Pickup interval must be between 1 minute and 365 days (525600 minutes)'; + +export function pickupProblem(minutes) { + const valid = Number.isFinite(minutes) && minutes >= 1 && minutes <= MAX_PICKUP_MINUTES; + return valid ? null : PICKUP_MESSAGE; +} + +export const toHours = (duration) => Number((seconds(duration) / 3600).toFixed(4)); export function formatInterval(duration) { const total = seconds(duration); @@ -30,7 +53,9 @@ export function bytes(size) { } export function relativeTime(iso) { - const elapsed = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000)); + const time = new Date(iso).getTime(); + if (!Number.isFinite(time)) return '—'; + const elapsed = Math.max(0, Math.floor((Date.now() - time) / 1000)); if (elapsed < 60) return `${elapsed}s ago`; const minutes = Math.floor(elapsed / 60); if (minutes < 60) return `${minutes}m ago`; diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js index 6925e08..307ea51 100644 --- a/src/main/resources/static/js/main.js +++ b/src/main/resources/static/js/main.js @@ -1,9 +1,11 @@ +import { initAuth } from './auth.js'; import { initBackups } from './backups.js'; import { initConnection } from './connection.js'; -import { applyEvent, canLoadBackups, emptyState } from './dashboard-model.js'; +import { applyEvent, canLoadBackups, emptyState, needsPairing } from './dashboard-model.js'; import { initEvents } from './events.js'; -import { api } from './api.js'; +import { api, loginRequired, onPairingRequired } from './api.js'; import { createNotifier } from './notify.js'; +import { initPairing } from './pairing.js'; import { initPickupInterval } from './pickup-interval.js'; import { initServerConfig } from './server-config.js'; import { initViews } from './views.js'; @@ -13,6 +15,12 @@ const DASHBOARD_REFRESH_MS = 60000; const notify = createNotifier(document.getElementById('banner')); const pickupInterval = initPickupInterval(document.getElementById('pickupIntervalForm'), notify); +const auth = initAuth({ + root: document.getElementById('auth'), + logoutButton: document.querySelector('[data-logout]'), + background: document.querySelectorAll('.topbar, .page'), +}); +const pairing = initPairing(document.getElementById('pairing'), notify, { resync: () => resync() }); const serverConfig = initServerConfig(document.querySelector('[data-view="config"]'), notify); const versions = initVersions(document.getElementById('versions')); const backups = initBackups({ @@ -28,6 +36,8 @@ const connection = initConnection({ let state = emptyState(); let pushes = 0; let pickupLoad = 'idle'; +let snapshots = 0; +let backupsAvailable = false; function loadPickupInterval() { if (pickupLoad !== 'idle') return; @@ -47,37 +57,50 @@ function dispatch(name, payload) { state = next; if (!unchanged) { connection.render(state); + pairing.render(state); backups.setServerRunning(state.running === true); + syncBackupsAvailability(); if (state.loaded) versions.render(state.versions); } - if (effects.clearBackups) backups.clear(); + if (effects.clearBackups) backups.reset(); if (effects.serverChanged) serverConfig.serverChanged(); if (effects.refreshBackups) backups.refresh(); if (state.loaded && state.clientReachable) loadPickupInterval(); } +function syncBackupsAvailability() { + const available = canLoadBackups(state); + backups.setPairingNeeded(needsPairing(state) && state.activeServer !== null); + if (backupsAvailable && !available) { + if (needsPairing(state)) backups.reset(); + else backups.clear(); + } + backupsAvailable = available; + backups.setAvailable(available); +} + async function resync() { const startedAt = pushes; + const mine = ++snapshots; try { const snapshot = await api.dashboard(); - if (pushes === startedAt) dispatch('snapshot', snapshot); + if (pushes === startedAt && mine === snapshots) dispatch('snapshot', snapshot); } catch (error) { - if (error instanceof TypeError && pushes === startedAt) dispatch('client', { reachable: false }); + if (error instanceof TypeError && pushes === startedAt && mine === snapshots) dispatch('client', { reachable: false }); } } +onPairingRequired(() => resync()); + +async function checkSession() { + const status = await api.authStatus(); + if (status && status.authenticated === false) loginRequired(); +} + function refreshBackupsIfUp() { if (canLoadBackups(state)) backups.refresh(); } -initEvents({ - onEvent: (name, payload) => { - pushes++; - dispatch(name, payload); - }, - onConnection: (reachable) => dispatch('client', { reachable }), -}); - document.addEventListener('click', (event) => { const button = event.target.closest('button'); if (!button) return; @@ -85,29 +108,42 @@ document.addEventListener('click', (event) => { setTimeout(() => button.classList.remove('clicked'), 140); }); -let viewShown = false; -initViews((view) => { - notify.clear(); - if (view === 'config') serverConfig.load(); - else if (viewShown) { - resync(); - refreshBackupsIfUp(); - } - viewShown = true; -}); +function start() { + initEvents({ + onEvent: (name, payload) => { + pushes++; + dispatch(name, payload); + }, + onConnection: (reachable) => dispatch('client', { reachable }), + checkSession, + }); -loadPickupInterval(); -resync(); + let viewShown = false; + initViews((view) => { + notify.clear(); + if (view === 'config') serverConfig.load(); + else if (viewShown) { + resync(); + refreshBackupsIfUp(); + } + viewShown = true; + }); -setInterval(() => { - if (document.hidden) return; + loadPickupInterval(); resync(); - if (location.hash === '#config') return; - backups.rerender(); -}, DASHBOARD_REFRESH_MS); -document.addEventListener('visibilitychange', () => { - if (document.hidden) return; - resync(); - if (location.hash !== '#config') refreshBackupsIfUp(); -}); + setInterval(() => { + if (document.hidden) return; + resync(); + if (location.hash === '#config') return; + backups.rerender(); + }, DASHBOARD_REFRESH_MS); + + document.addEventListener('visibilitychange', () => { + if (document.hidden) return; + resync(); + if (location.hash !== '#config') refreshBackupsIfUp(); + }); +} + +if (await auth.ensureSignedIn()) start(); diff --git a/src/main/resources/static/js/notify.js b/src/main/resources/static/js/notify.js index ddbe743..b77b08f 100644 --- a/src/main/resources/static/js/notify.js +++ b/src/main/resources/static/js/notify.js @@ -2,10 +2,13 @@ export function createNotifier(banner) { function show(message, kind) { banner.textContent = message; banner.className = `banner visible ${kind}`; + banner.setAttribute('aria-live', kind === 'error' ? 'assertive' : 'polite'); + if (kind !== 'ok' && banner.scrollIntoView) banner.scrollIntoView({ block: 'nearest' }); } return { ok: (message) => show(message, 'ok'), + warn: (message) => show(message, 'warn'), error: (error) => show(error.message || String(error), 'error'), clear: () => { banner.className = 'banner'; }, }; diff --git a/src/main/resources/static/js/pairing-model.js b/src/main/resources/static/js/pairing-model.js new file mode 100644 index 0000000..dd796d7 --- /dev/null +++ b/src/main/resources/static/js/pairing-model.js @@ -0,0 +1,31 @@ +import { needsPairing } from './dashboard-model.js'; + +function reachable(link) { + return link === 'LIVE' || link === 'DEGRADED'; +} + +export function pairingPanel(state) { + if (!state.loaded || !state.clientReachable || state.activeServer === null) return 'hidden'; + if (!reachable(state.link)) return 'hidden'; + return needsPairing(state) ? 'pair' : 'manage'; +} + +export function pairingNote(state) { + if (state.pairing === 'REJECTED') { + return 'The server no longer accepts this client. Enter a pairing code from a client that is still paired. The Pairing PIN (logged by the server) works only when no client is paired, or after MEDIAGARRD_OPEN_PAIRING.'; + } + return 'Enter the Pairing PIN (shown after Finish Setup and in the server logs), or a pairing code created by a client that is already paired.'; +} + +export function credentialProblem(value) { + return String(value ?? '').trim() ? null : 'Enter the PIN or pairing code.'; +} + +export function codeView(code, now) { + if (!code) return null; + const left = Math.max(0, Math.round((Date.parse(code.expiresAt) - now) / 1000)); + if (!Number.isFinite(left) || left <= 0) return { text: code.code, expires: 'Expired' }; + const minutes = Math.floor(left / 60); + const seconds = left % 60; + return { text: code.code, expires: `Expires in ${minutes}:${String(seconds).padStart(2, '0')}` }; +} diff --git a/src/main/resources/static/js/pairing.js b/src/main/resources/static/js/pairing.js new file mode 100644 index 0000000..64cd032 --- /dev/null +++ b/src/main/resources/static/js/pairing.js @@ -0,0 +1,94 @@ +import { api } from './api.js'; +import { withBusy } from './busy.js'; +import { codeView, credentialProblem, pairingNote, pairingPanel } from './pairing-model.js'; + +export function initPairing(root, notify, { resync }) { + const pairForm = root.querySelector('[data-pair-form]'); + const manage = root.querySelector('[data-manage]'); + const note = root.querySelector('[data-pair-note]'); + const codeBox = root.querySelector('[data-code-box]'); + const codeText = root.querySelector('[data-code]'); + const codeExpiry = root.querySelector('[data-code-expiry]'); + const createCode = root.querySelector('[data-create-code]'); + const unpair = root.querySelector('[data-unpair]'); + let code = null; + let timer = null; + + function renderCode() { + const view = codeView(code, Date.now()); + codeBox.hidden = !view; + if (!view) return; + codeText.textContent = view.text; + codeExpiry.textContent = view.expires; + } + + function forgetCode() { + code = null; + clearInterval(timer); + timer = null; + renderCode(); + } + + function render(state) { + const panel = pairingPanel(state); + root.hidden = panel === 'hidden'; + pairForm.hidden = panel !== 'pair'; + manage.hidden = panel !== 'manage'; + if (panel === 'pair') note.textContent = pairingNote(state); + if (panel !== 'manage') forgetCode(); + } + + pairForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const field = pairForm.elements.pin; + const problem = credentialProblem(field.value); + if (problem) { + notify.error(problem); + return; + } + notify.clear(); + await withBusy(pairForm.querySelector('button'), async () => { + try { + const result = await api.pair(field.value.trim()); + field.value = ''; + if (result?.note) notify.warn(result.note); + else notify.ok('Paired with the server'); + await resync(); + } catch (error) { + notify.error(error); + } + }); + }); + + createCode.addEventListener('click', async () => { + notify.clear(); + await withBusy(createCode, async () => { + try { + code = await api.createPairingCode(); + renderCode(); + clearInterval(timer); + timer = setInterval(renderCode, 1000); + } catch (error) { + notify.error(error); + } + }); + }); + + unpair.addEventListener('click', async () => { + if (!confirm('Unpair this client from the server? It will need a new PIN or pairing code to connect again.')) return; + notify.clear(); + await withBusy(unpair, async () => { + try { + const result = await api.unpair(); + forgetCode(); + if (result?.serverRevoked) notify.ok('Unpaired. The server no longer accepts this client.'); + else notify.warn(result?.warning || 'Unpaired locally, but the server could not be told to revoke this client. It may still list this client as paired; remove it with DELETE /api/v1/clients/{id} on the server.'); + await resync(); + } catch (error) { + notify.error(error); + } + }); + }); + + return { render }; +} diff --git a/src/main/resources/static/js/pickup-interval.js b/src/main/resources/static/js/pickup-interval.js index 342980b..6ce52e0 100644 --- a/src/main/resources/static/js/pickup-interval.js +++ b/src/main/resources/static/js/pickup-interval.js @@ -1,5 +1,5 @@ import { api } from './api.js'; -import { seconds, toDuration } from './format.js'; +import { pickupProblem, seconds, toDuration } from './format.js'; export function initPickupInterval(form, notify) { const minutes = form.elements.minutes; @@ -10,6 +10,11 @@ export function initPickupInterval(form, notify) { form.addEventListener('submit', async (event) => { event.preventDefault(); notify.clear(); + const problem = pickupProblem(Number(minutes.value)); + if (problem) { + notify.error(new Error(problem)); + return; + } try { const status = await api.updatePickupInterval(toDuration(Number(minutes.value))); edited = false; diff --git a/src/main/resources/static/js/server-config.js b/src/main/resources/static/js/server-config.js index 9a46998..027edda 100644 --- a/src/main/resources/static/js/server-config.js +++ b/src/main/resources/static/js/server-config.js @@ -1,25 +1,33 @@ import { api } from './api.js'; import { initServices } from './services.js'; +import { initWebhook } from './webhook.js'; import { initSettings } from './settings.js'; +import { configUnavailableMessage } from './view-model.js'; export function initServerConfig(root, notify) { const content = root.querySelector('[data-config-content]'); const unavailable = root.querySelector('[data-unavailable]'); const settings = initSettings(root.querySelector('#settingsForm'), notify); + const webhook = initWebhook(root.querySelector('#webhookForm'), notify); const services = initServices(root.querySelector('#services'), notify); + let latestLoad = 0; + async function load() { + const mine = ++latestLoad; try { const [config, list] = await Promise.all([api.serverConfig(), api.listServices()]); + if (mine !== latestLoad) return; settings.show(config); services.show(list); + webhook.load(); content.hidden = false; unavailable.hidden = true; } catch (error) { + if (mine !== latestLoad) return; content.hidden = true; unavailable.hidden = false; - unavailable.querySelector('[data-reason]').textContent = - `${error.message}. Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; + unavailable.querySelector('[data-reason]').textContent = configUnavailableMessage(error); } } @@ -27,6 +35,7 @@ export function initServerConfig(root, notify) { load, serverChanged() { services.resetForm(); + webhook.reset(); if (!root.hidden) load(); }, }; diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js index 0c0ab09..ebfa8e5 100644 --- a/src/main/resources/static/js/services.js +++ b/src/main/resources/static/js/services.js @@ -46,10 +46,19 @@ export function initServices(root, notify) { try { await api.removeService(service.name); if (editing === service.name) resetForm(); - notify.ok(`Removed ${service.name}`); - await refresh(); } catch (error) { notify.error(error); + return; + } + await refreshThen(`Removed ${service.name}`); + } + + async function refreshThen(message) { + try { + await refresh(); + notify.ok(message); + } catch (error) { + notify.warn(`${message}, but the list could not be refreshed: ${error.message}`); } } @@ -78,14 +87,15 @@ export function initServices(root, notify) { name: form.elements.name.value, paths: [...paths.querySelectorAll('input')].map((input) => input.value), }; + let saved; try { - const saved = editing ? await api.updateService(editing, service) : await api.addService(service); - notify.ok(`Saved ${saved.name}`); + saved = editing ? await api.updateService(editing, service) : await api.addService(service); resetForm(); - await refresh(); } catch (error) { notify.error(error); + return; } + await refreshThen(`Saved ${saved.name}`); }); root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js index cd2cf08..7602b25 100644 --- a/src/main/resources/static/js/settings.js +++ b/src/main/resources/static/js/settings.js @@ -1,18 +1,23 @@ import { api } from './api.js'; -import { seconds, toDuration } from './format.js'; +import { intervalProblem, toDuration, toHours } from './format.js'; export function initSettings(form, notify) { const { backupLocation, intervalHours, retentionCount } = form.elements; function show(config) { backupLocation.value = config.backupLocation; - intervalHours.value = seconds(config.backupInterval) / 3600; + intervalHours.value = toHours(config.backupInterval); retentionCount.value = config.retentionCount; } form.addEventListener('submit', async (event) => { event.preventDefault(); notify.clear(); + const problem = intervalProblem(Number(intervalHours.value)); + if (problem) { + notify.error(new Error(problem)); + return; + } try { show(await api.updateServerConfig({ backupLocation: backupLocation.value, diff --git a/src/main/resources/static/js/view-model.js b/src/main/resources/static/js/view-model.js index 6f385ab..f7057cf 100644 --- a/src/main/resources/static/js/view-model.js +++ b/src/main/resources/static/js/view-model.js @@ -1,7 +1,21 @@ +import { needsPairing } from './dashboard-model.js'; import { formatInterval } from './format.js'; const RELEASE_URL = /^https?:\/\//; +export function listingError(error, connected) { + const message = /[.!?]$/.test(error.message) ? error.message : `${error.message}.`; + return connected ? message : `${message} Connect to a server to view archives.`; +} + +export function configUnavailableMessage(error) { + if (error?.pairing === 'required') { + return 'Pair this client with the server on the Dashboard to manage its configuration.'; + } + const message = /[.!?]$/.test(error.message) ? error.message : `${error.message}.`; + return `${message} Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; +} + export function linkView(state) { const none = { showDetails: false, url: '', interval: '—', retention: '—', running: false, degraded: false }; if (!state.clientReachable) { @@ -19,8 +33,14 @@ export function linkView(state) { if (state.link === 'DOWN') { return { ...none, badge: { kind: 'down', label: 'Unreachable' }, message: `${state.activeServer} is not responding.` }; } + if (needsPairing(state)) { + const message = state.pairing === 'REJECTED' + ? `${state.activeServer} rejected this client's token. Pair again to continue.` + : `This client is not paired with ${state.activeServer}.`; + return { ...none, badge: { kind: 'down', label: 'Pairing required' }, message }; + } return { - badge: { kind: 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, + badge: { kind: state.link === 'DEGRADED' ? 'degraded' : 'ok', label: state.activeServer.replace(/^https?:\/\//, '') }, message: '', showDetails: true, url: state.activeServer, diff --git a/src/main/resources/static/js/webhook.js b/src/main/resources/static/js/webhook.js new file mode 100644 index 0000000..77fed6b --- /dev/null +++ b/src/main/resources/static/js/webhook.js @@ -0,0 +1,103 @@ +import { api } from './api.js'; +import { withBusy } from './busy.js'; + +export function describeStatus(status) { + return status && status.configured ? `Configured: ${status.target}` : 'Not configured'; +} + +export function describeTest(result) { + if (result && result.delivered) return { ok: true, message: 'Test message delivered' }; + const reason = result && result.error ? result.error : 'no reason given'; + return { ok: false, message: `Test message was not delivered: ${reason}` }; +} + +export function initWebhook(form, notify) { + const { url } = form.elements; + const label = form.querySelector('[data-webhook-status]'); + const testButton = form.querySelector('[data-webhook-test]'); + const clearButton = form.querySelector('[data-webhook-clear]'); + const saveButton = form.querySelector('button[type="submit"]'); + let latest = 0; + + function show(status) { + label.textContent = describeStatus(status); + url.value = ''; + } + + async function load() { + const mine = ++latest; + label.textContent = 'Checking…'; + try { + const status = await api.webhook(); + if (mine === latest) label.textContent = describeStatus(status); + } catch (error) { + if (mine === latest) label.textContent = `Unavailable: ${error.message}`; + } + } + + function reset() { + latest++; + url.value = ''; + label.textContent = 'Checking…'; + } + + async function save(value) { + const mine = latest; + const status = await api.updateWebhook(value); + if (mine === latest) show(status); + } + + async function exclusive(button, task) { + const others = [saveButton, testButton, clearButton].filter((other) => other !== button); + if (others.some((other) => other.disabled)) return; + others.forEach((other) => { other.disabled = true; }); + try { + await withBusy(button, task); + } finally { + others.forEach((other) => { other.disabled = false; }); + } + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const value = url.value.trim(); + if (!value) { + notify.error(new Error('Enter a webhook URL, or use Clear to turn notifications off')); + return; + } + await exclusive(saveButton, async () => { + try { + await save(value); + notify.ok('Webhook saved'); + } catch (error) { + notify.error(error); + } + }); + }); + + clearButton.addEventListener('click', () => exclusive(clearButton, async () => { + notify.clear(); + try { + await save(''); + notify.ok('Webhook cleared'); + } catch (error) { + notify.error(error); + } + })); + + testButton.addEventListener('click', () => exclusive(testButton, async () => { + notify.clear(); + try { + const typed = url.value.trim(); + if (typed) await save(typed); + const outcome = describeTest(await api.testWebhook()); + if (outcome.ok) notify.ok(outcome.message); + else notify.error(new Error(outcome.message)); + } catch (error) { + notify.error(error); + } + })); + + return { load, reset, show }; +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java deleted file mode 100644 index 4080d24..0000000 --- a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java +++ /dev/null @@ -1,74 +0,0 @@ -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; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.web.servlet.MockMvc; - -@SpringBootTest -@AutoConfigureMockMvc -class MediaGarrdTest { - - @TempDir - static Path dataDir; - - @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 - void servesTheWebPageAndItsAssets() throws Exception { - mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); - mockMvc.perform(get("/css/mediagarrd.css")) - .andExpect(status().isOk()) - .andExpect(header().string("Cache-Control", "no-store")); - mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); - } - - @Test - void reportsStatusWithoutAServer() throws Exception { - mockMvc.perform(get("/api/client/status")) - .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/ApiExceptionHandlerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java new file mode 100644 index 0000000..8ae3b77 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ApiExceptionHandlerTest.java @@ -0,0 +1,130 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.service.ConflictException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; +import wellatleastitried.mediagarrdclient.service.UpstreamResponseException; + +class ApiExceptionHandlerTest { + + private final ApiExceptionHandler handler = new ApiExceptionHandler(); + + @Test + void anUnexpectedFailureAnswersWithAGenericMessageInsteadOfItsDetails() { + var response = handler.failed(new IllegalStateException("Failed to save client state to /var/lib/mediagarrd/client/state.json")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void aRejectedRequestKeepsItsMessage() { + var response = handler.invalid(new InvalidRequestException("PIN must be 6 digits")); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals(Map.of("error", "PIN must be 6 digits"), response.getBody()); + } + + @Test + void anIllegalArgumentIsNotMistakenForARejectedRequest() { + var response = handler.failed(new IllegalArgumentException("/var/lib/mediagarrd is not a directory")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void notFoundAndConflictKeepTheirMessagesAndStatuses() { + var missing = handler.notFound(new NotFoundException("Backup not found: b9")); + var conflict = handler.conflict(new ConflictException("A password is already set")); + + assertEquals(HttpStatus.NOT_FOUND, missing.getStatusCode()); + assertEquals(Map.of("error", "Backup not found: b9"), missing.getBody()); + assertEquals(HttpStatus.CONFLICT, conflict.getStatusCode()); + assertEquals(Map.of("error", "A password is already set"), conflict.getBody()); + } + + @Test + void aSpringErrorResponseKeepsItsClientStatusAndDetail() { + var response = handler.failed(new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertEquals(Map.of("error", "Pickup task not found: gone"), response.getBody()); + } + + @Test + void aSpringServerErrorResponseBecomesTheGenericBody() { + var response = handler.failed(new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "/etc/secret is missing")); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "Internal error"), response.getBody()); + } + + @Test + void aServerFailureIsNotReflectedBack() { + var response = handler.serverRejected(new org.springframework.web.client.HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error", "{\"error\":\"Disk /srv/backups is full\"}".getBytes(), java.nio.charset.StandardCharsets.UTF_8)); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertEquals(Map.of("error", "MediaGarrd server responded with 500"), response.getBody()); + } + + @Test + void anUnusableServerReplyIsABadGateway() { + var response = handler.upstreamInvalid(new UpstreamResponseException("The server did not return a token")); + + assertEquals(HttpStatus.BAD_GATEWAY, response.getStatusCode()); + assertEquals(Map.of("error", "The server did not return a token"), response.getBody()); + } + + private static org.springframework.web.client.HttpClientErrorException tooManyRequests(String retryAfter, String body) { + org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); + if (retryAfter != null) { + headers.add("Retry-After", retryAfter); + } + var e = org.springframework.web.client.HttpClientErrorException.create( + HttpStatus.TOO_MANY_REQUESTS, "Too Many Requests", headers, new byte[0], java.nio.charset.StandardCharsets.UTF_8); + e.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError(body)); + return e; + } + + @Test + void aProxiedTooManyRequestsKeepsItsRetryAfterAndMessage() { + var response = handler.serverRejected(tooManyRequests("7", "Wait 7 seconds before sending another test")); + + assertEquals(HttpStatus.TOO_MANY_REQUESTS, response.getStatusCode()); + assertEquals("7", response.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Wait 7 seconds before sending another test"), response.getBody()); + } + + @Test + void aProxiedTooManyRequestsWithoutAUsableRetryAfterHasNone() { + var missing = handler.serverRejected(tooManyRequests(null, "Slow down")); + var odd = handler.serverRejected(tooManyRequests("soon\r\nX-Evil: 1", "Slow down")); + + assertEquals(HttpStatus.TOO_MANY_REQUESTS, missing.getStatusCode()); + assertEquals(null, missing.getHeaders().getFirst("Retry-After")); + assertEquals(null, odd.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Slow down"), odd.getBody()); + } + + @Test + void otherProxiedRejectionsGetNoRetryAfter() { + var rejected = org.springframework.web.client.HttpClientErrorException.create( + HttpStatus.BAD_REQUEST, "Bad Request", new org.springframework.http.HttpHeaders(), new byte[0], java.nio.charset.StandardCharsets.UTF_8); + rejected.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError("Webhook URL must use http or https")); + var response = handler.serverRejected(rejected); + + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); + assertEquals(null, response.getHeaders().getFirst("Retry-After")); + assertEquals(Map.of("error", "Webhook URL must use http or https"), response.getBody()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java new file mode 100644 index 0000000..21fb808 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthControllerConcurrencyTest.java @@ -0,0 +1,151 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; + +import wellatleastitried.mediagarrdclient.dto.PasswordRequest; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@Timeout(30) +class AuthControllerConcurrencyTest { + + private static MockHttpServletRequest from(String address) { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/auth/login"); + request.setRemoteAddr(address); + return request; + } + + @Test + void parallelWrongLoginsFromOneSourceReachThePasswordCheckAtMostOnce() throws Exception { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + AtomicInteger checks = new AtomicInteger(); + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(passwords.matches(any())).thenAnswer(call -> { + checks.incrementAndGet(); + inside.countDown(); + release.await(10, TimeUnit.SECONDS); + return false; + }); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + ExecutorService pool = Executors.newFixedThreadPool(8); + List> results = new ArrayList<>(); + CountDownLatch refused = new CountDownLatch(7); + for (int i = 0; i < 8; i++) { + results.add(pool.submit(() -> { + int status = controller.login(new PasswordRequest("guess"), from("10.2.0.1")).getStatusCode().value(); + if (status == 429) { + refused.countDown(); + } + return status; + })); + } + assertTrue(inside.await(10, TimeUnit.SECONDS)); + assertTrue(refused.await(10, TimeUnit.SECONDS)); + release.countDown(); + List statuses = new ArrayList<>(); + for (Future result : results) { + statuses.add(result.get(10, TimeUnit.SECONDS)); + } + pool.shutdownNow(); + + assertEquals(1, checks.get()); + assertEquals(1, statuses.stream().filter(status -> status == 401).count()); + assertEquals(7, statuses.stream().filter(status -> status == 429).count()); + } + + @Test + void onlyAFewPasswordChecksRunAtOnceAcrossSources() throws Exception { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + AtomicInteger running = new AtomicInteger(); + AtomicInteger peak = new AtomicInteger(); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch started = new CountDownLatch(3); + when(passwords.matches(any())).thenAnswer(call -> { + peak.accumulateAndGet(running.incrementAndGet(), Math::max); + started.countDown(); + release.await(10, TimeUnit.SECONDS); + running.decrementAndGet(); + return false; + }); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + ExecutorService pool = Executors.newFixedThreadPool(10); + List> results = new ArrayList<>(); + CountDownLatch refused = new CountDownLatch(7); + for (int i = 0; i < 10; i++) { + String source = "10.3.0." + i; + results.add(pool.submit(() -> { + int status = controller.login(new PasswordRequest("guess"), from(source)).getStatusCode().value(); + if (status == 429) { + refused.countDown(); + } + return status; + })); + } + assertTrue(started.await(10, TimeUnit.SECONDS)); + assertTrue(refused.await(10, TimeUnit.SECONDS)); + release.countDown(); + long refusedCount = 0; + for (Future result : results) { + if (result.get(10, TimeUnit.SECONDS) == 429) { + refusedCount++; + } + } + pool.shutdownNow(); + + assertEquals(3, peak.get()); + assertEquals(7, refusedCount); + } + + @Test + void anErrorFromThePasswordCheckReleasesTheSourceSoItCanTryAgain() { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + when(passwords.matches(any())).thenThrow(new StackOverflowError()).thenReturn(true); + AuthController controller = new AuthController(passwords, new SessionService(), new LoginAttempts()); + + assertThrows(StackOverflowError.class, () -> controller.login(new PasswordRequest("guess"), from("10.4.0.1"))); + + assertEquals(200, controller.login(new PasswordRequest("guess"), from("10.4.0.1")).getStatusCode().value()); + } + + @Test + void aFinishedLoginDoesNotReleaseTheReservationOfTheNextAttemptFromTheSameSource() { + PasswordService passwords = mock(PasswordService.class); + when(passwords.isConfigured()).thenReturn(true); + when(passwords.matches(any())).thenReturn(true); + LoginAttempts attempts = new LoginAttempts(); + SessionService sessions = mock(SessionService.class); + when(sessions.create()).thenAnswer(call -> { + assertTrue(attempts.tryBegin("10.4.0.2").isEmpty()); + return "token"; + }); + AuthController controller = new AuthController(passwords, sessions, attempts); + + assertEquals(200, controller.login(new PasswordRequest("guess"), from("10.4.0.2")).getStatusCode().value()); + + assertTrue(attempts.tryBegin("10.4.0.2").isPresent()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java new file mode 100644 index 0000000..ee9937a --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/AuthGateFullContextTest.java @@ -0,0 +1,333 @@ +package wellatleastitried.mediagarrdclient.api; + +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.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request; +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.net.URI; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import jakarta.servlet.http.Cookie; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +@SpringBootTest +@org.springframework.context.annotation.Import(wellatleastitried.mediagarrdclient.api.TestCsrfHeader.class) +@AutoConfigureMockMvc +class AuthGateFullContextTest { + + private static final String PASSWORD = "correct horse battery"; + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @Autowired + MediaGarrdProperties configuration; + + @Autowired + @Qualifier("requestMappingHandlerMapping") + RequestMappingHandlerMapping mappings; + + @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"); + registry.add("mediagarrd.client.password", () -> PASSWORD); + } + + private static String loginBody(String password) { + return "{\"password\":\"" + password + "\"}"; + } + + private MvcResult login(String source, String password) throws Exception { + return mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr(source); + return request; + }) + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(password))) + .andReturn(); + } + + private Cookie signIn(String source) throws Exception { + MvcResult result = login(source, PASSWORD); + assertEquals(200, result.getResponse().getStatus()); + return result.getResponse().getCookie("mg_session"); + } + + @Test + void everyRegisteredHandlerRefusesARequestWithoutASessionExceptTheAuthEndpoints() throws Exception { + Set checkedPublic = new TreeSet<>(); + Set checkedProtected = new TreeSet<>(); + for (var entry : mappings.getHandlerMethods().entrySet()) { + RequestMappingInfo info = entry.getKey(); + HandlerMethod handler = entry.getValue(); + boolean open = handler.hasMethodAnnotation(PublicEndpoint.class); + Set methods = info.getMethodsCondition().getMethods(); + for (String pattern : info.getPathPatternsCondition().getPatternValues()) { + for (HttpMethod method : methods.isEmpty() ? List.of(HttpMethod.GET) : methods.stream().map(m -> HttpMethod.valueOf(m.name())).toList()) { + String path = pattern.replaceAll("\\{[^/}]+}", "x"); + MvcResult result = mockMvc.perform(request(method, URI.create(path)) + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andReturn(); + String label = method + " " + path; + if (open) { + assertFalse(result.getResponse().getContentAsString().contains("\"login\":\"required\""), label + " should be reachable without a session"); + checkedPublic.add(label); + } else { + assertEquals(401, result.getResponse().getStatus(), label + " should require a session"); + assertTrue(result.getResponse().getContentAsString().contains("\"login\":\"required\""), label); + checkedProtected.add(label); + } + } + } + } + + assertEquals(Set.of("GET /api/auth/status", "POST /api/auth/login", "POST /api/auth/set-password", "POST /api/auth/logout"), checkedPublic); + assertTrue(checkedProtected.contains("GET /api/client/events"), checkedProtected.toString()); + assertTrue(checkedProtected.contains("POST /api/client/pairing"), checkedProtected.toString()); + assertTrue(checkedProtected.contains("GET /api/client/dashboard"), checkedProtected.toString()); + assertTrue(checkedProtected.stream().noneMatch(label -> label.contains("/api/auth/")), checkedProtected.toString()); + } + + @Test + void pathVariantsOfAProtectedEndpointNeverBypassTheGate() throws Exception { + List variants = new ArrayList<>(List.of( + "/api/client/status;x", + "/api/client/status;jsessionid=1", + "/api/client/%73tatus", + "/api/client/status/", + "//api/client/status", + "///api/client/status", + "/api/client/./status", + "/api/client/%2e/status", + "/api/client/x/../status", + "/api/client/status%2f", + "/api/client/status%3bx", + "/API/CLIENT/STATUS", + "/api;x/client/status", + "/api/client;x/status", + "/api/client/status.json", + "/api/client/status?x=1")); + for (String variant : variants) { + MvcResult result = mockMvc.perform(get(URI.create(variant))).andReturn(); + int status = result.getResponse().getStatus(); + assertFalse(status / 100 == 2, variant + " answered " + status + " without a session"); + assertFalse(result.getResponse().getContentAsString().contains("activeServer"), variant); + } + } + + @Test + void aMatrixParameterVariantReachesTheHandlerSoTheGateReallyDecidedIt() throws Exception { + Cookie cookie = signIn("10.1.0.1"); + + mockMvc.perform(get(URI.create("/api/client/status;x")).cookie(cookie)).andExpect(status().isOk()); + mockMvc.perform(get(URI.create("/api/client/status;x"))).andExpect(status().isUnauthorized()); + } + + @Test + void theWebPageAndItsAssetsAreServedWithoutASession() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/index.html")).andExpect(status().isOk()); + mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); + mockMvc.perform(get("/js/auth.js")).andExpect(status().isOk()); + mockMvc.perform(get("/css/mediagarrd.css")) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", "no-store")); + } + + @Test + void bindsTheBackupRunTimeoutDefault() { + assertEquals(Duration.ofHours(6), configuration.getBackupRunTimeout()); + } + + @Test + void reportsStatusWithoutAServer() throws Exception { + mockMvc.perform(get("/api/client/status").cookie(signIn("10.1.0.21"))) + .andExpect(status().isOk()) + .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); + } + + @Test + void reportsTheDashboardWithTheClientVersionAndNoServer() throws Exception { + mockMvc.perform(get("/api/client/dashboard").cookie(signIn("10.1.0.22"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.link").value("DOWN")) + .andExpect(jsonPath("$.activeServer").doesNotExist()) + .andExpect(jsonPath("$.versions.client.checkState").exists()) + .andExpect(jsonPath("$.versions.server").doesNotExist()) + .andExpect(jsonPath("$.pairing").value("NONE")); + } + + @Test + void reportsWhetherThePasswordIsSetAndWhoComesFromTheEnvironment() throws Exception { + mockMvc.perform(get("/api/auth/status")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.passwordSet").value(true)) + .andExpect(jsonPath("$.passwordFromEnvironment").value(true)) + .andExpect(jsonPath("$.authenticated").value(false)); + mockMvc.perform(get("/api/auth/status").cookie(signIn("10.1.0.2"))) + .andExpect(jsonPath("$.authenticated").value(true)); + } + + @Test + void aWrongPasswordIsRefusedWithoutTheLoginRequiredMarker() throws Exception { + MvcResult result = login("10.1.0.3", "wrong password"); + + assertEquals(401, result.getResponse().getStatus()); + assertEquals("{\"error\":\"Incorrect password\"}", result.getResponse().getContentAsString()); + assertEquals(null, result.getResponse().getCookie("mg_session")); + } + + @Test + void theSessionCookieIsHttpOnlySameSiteStrictAndSecureOnlyOverHttps() throws Exception { + String plain = login("10.1.0.4", PASSWORD).getResponse().getHeader("Set-Cookie"); + String forwarded = mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr("10.1.0.5"); + return request; + }) + .header("X-Forwarded-Proto", "https") + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(PASSWORD))) + .andReturn().getResponse().getHeader("Set-Cookie"); + String direct = mockMvc.perform(post("/api/auth/login") + .with(request -> { + request.setRemoteAddr("10.1.0.6"); + request.setSecure(true); + return request; + }) + .contentType(MediaType.APPLICATION_JSON) + .content(loginBody(PASSWORD))) + .andReturn().getResponse().getHeader("Set-Cookie"); + + assertNotNull(plain); + assertTrue(plain.contains("HttpOnly") && plain.contains("SameSite=Strict") && plain.contains("Path=/"), plain); + assertFalse(plain.contains("Secure"), plain); + assertTrue(forwarded.contains("Secure") && forwarded.contains("HttpOnly") && forwarded.contains("SameSite=Strict"), forwarded); + assertTrue(direct.contains("Secure"), direct); + } + + @Test + void repeatedFailuresLockTheSourceOutWithA429EvenForTheRightPassword() throws Exception { + for (int i = 0; i < 4; i++) { + assertEquals(401, login("10.1.0.7", "wrong password " + i).getResponse().getStatus()); + } + + MvcResult locked = login("10.1.0.7", PASSWORD); + + assertEquals(429, locked.getResponse().getStatus()); + assertNotNull(locked.getResponse().getHeader("Retry-After")); + assertTrue(locked.getResponse().getContentAsString().contains("\"error\"")); + assertEquals(200, login("10.1.0.8", PASSWORD).getResponse().getStatus()); + } + + @Test + void aPasswordCannotBeSetWhileClientPasswordIsConfigured() throws Exception { + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(loginBody("another password"))) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void loggingOutEndsTheSession() throws Exception { + Cookie cookie = signIn("10.1.0.9"); + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isOk()); + + MvcResult logout = mockMvc.perform(post("/api/auth/logout").cookie(cookie)).andExpect(status().isNoContent()).andReturn(); + + assertTrue(logout.getResponse().getHeader("Set-Cookie").contains("Max-Age=0")); + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isUnauthorized()); + } + + @Test + void crossSiteWritesAreRefusedEvenWithAValidSession() throws Exception { + Cookie cookie = signIn("10.1.0.10"); + + mockMvc.perform(put("/api/client/pickup-interval").cookie(cookie).header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content("{\"interval\":\"PT1H\"}")) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/client/pairing").cookie(cookie).header("Sec-Fetch-Site", "cross-site") + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/auth/login").header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content(loginBody(PASSWORD))) + .andExpect(status().isForbidden()); + } + + @Test + void aWriteWithNeitherBrowserHeadersNorTheCustomHeaderIsRefused() throws Exception { + Cookie cookie = signIn("10.1.0.12"); + + mockMvc.perform(post("/api/client/pairing").cookie(cookie) + .with(request -> { + request.removeHeader("X-MediaGarrd-Request"); + return request; + }) + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"\"}")) + .andExpect(status().isForbidden()); + } + + @Test + void sameOriginWritesAreAccepted() throws Exception { + Cookie cookie = signIn("10.1.0.11"); + + mockMvc.perform(post("/api/client/pairing").cookie(cookie).header("Origin", "http://client.local:8081").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void everyResponseForbidsFraming() throws Exception { + for (String path : List.of("/", "/index.html", "/api/auth/status", "/api/client/status", "/no-such-page.html")) { + mockMvc.perform(get(path)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("X-Frame-Options", "DENY")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Content-Security-Policy", SecurityHeadersFilter.CONTENT_SECURITY_POLICY)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("X-Content-Type-Options", "nosniff")) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Referrer-Policy", "no-referrer")); + } + for (String path : List.of("/api/auth/status", "/api/client/status")) { + mockMvc.perform(get(path)) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.header().string("Cache-Control", "no-store")); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java new file mode 100644 index 0000000..88e0b2e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientApiGoldenTest.java @@ -0,0 +1,251 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.json.JsonCompareMode; +import org.springframework.test.web.servlet.MockMvc; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.DashboardState; +import wellatleastitried.mediagarrdclient.dto.HealthSummary; +import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.PairingState; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.dto.VersionsDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.DashboardService; +import wellatleastitried.mediagarrdclient.service.LoginAttempts; +import wellatleastitried.mediagarrdclient.service.PasswordService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; + +@WebMvcTest(controllers = {ClientController.class, PairingController.class, ServerConfigController.class, WebhookController.class, AuthController.class}) +@Import({TestSession.class, ServerSelectionService.class}) +class ClientApiGoldenTest { + + private static final String SERVER = "http://192.168.1.20:38471"; + private static final Instant INSTANT = Instant.parse("2026-11-20T10:15:30.123456Z"); + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerDiscoveryService discoveryService; + + @MockitoBean + ServerApiService serverApiService; + + @MockitoBean + BackupPickupService backupPickupService; + + @MockitoBean + DashboardService dashboardService; + + @MockitoBean + ClientPairingService pairing; + + @MockitoBean + PasswordService passwords; + + @MockitoBean + LoginAttempts attempts; + + @Test + void statusJson() throws Exception { + when(stateService.getActiveServer()).thenReturn(SERVER); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(90)); + when(stateService.getKnownServers()).thenReturn(List.of(SERVER, "https://backup.example.net:38471")); + + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/status.json"), JsonCompareMode.STRICT)); + } + + @Test + void dashboardJson() throws Exception { + VersionStatusDto client = new VersionStatusDto("0.1.0", "0.1.0", "https://github.com/MediaGarrd/Client/releases/tag/v0.1.0", false, CheckState.OK, INSTANT, null); + when(dashboardService.state()).thenReturn(new DashboardState(SERVER, List.of(SERVER), LinkState.LIVE, false, + new HealthSummary(Duration.ofHours(6), 7), new VersionsDto(client, null), PairingState.PAIRED)); + + mockMvc.perform(get("/api/client/dashboard")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/dashboard.json"), JsonCompareMode.STRICT)); + } + + @Test + void backupsJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.listBackups(SERVER)).thenReturn(List.of(new BackupDto("backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L, INSTANT))); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/backups.json"), JsonCompareMode.STRICT)); + } + + @Test + void serverConfigJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/var/backups/mediagarrd", 7, Duration.ofHours(6))); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/server-config.json"), JsonCompareMode.STRICT)); + } + + @Test + void webhookJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.webhook(SERVER)).thenReturn(new WebhookStatusDto(true, "https://discord.com")); + when(serverApiService.updateWebhook(SERVER, "")).thenReturn(new WebhookStatusDto(false, null)); + when(serverApiService.testWebhook(SERVER)).thenReturn(new WebhookTestDto(false, 404, "Webhook answered 404")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-status.json"), JsonCompareMode.STRICT)); + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-unset.json"), JsonCompareMode.STRICT)); + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/webhook-test.json"), JsonCompareMode.STRICT)); + } + + @Test + void serverConfigUpdateParsesADurationString() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.updateServerConfig(SERVER, "/b", 3)).thenReturn(new ServerConfigDto("/b", 3, Duration.ofHours(6))); + when(serverApiService.updateServerSchedule(SERVER, Duration.ofHours(2))).thenReturn(new ServerStatusDto(true, false, 3, Duration.ofHours(2))); + + mockMvc.perform(put("/api/client/server-config").contentType(MediaType.APPLICATION_JSON) + .content("{\"backupLocation\":\"/b\",\"retentionCount\":3,\"backupInterval\":\"PT2H\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"backupLocation\":\"/b\",\"retentionCount\":3,\"backupInterval\":\"PT2H\"}", JsonCompareMode.STRICT)); + } + + @Test + void servicesJson() throws Exception { + when(stateService.requireActiveServer()).thenReturn(SERVER); + when(serverApiService.listServices(SERVER)).thenReturn(List.of(new ServiceDto("jellyfin", List.of("/srv/jellyfin/config")))); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/services.json"), JsonCompareMode.STRICT)); + } + + @Test + void pickupJson() throws Exception { + when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L)); + when(backupPickupService.pickupProgress("task-1")).thenReturn(new PickupProgressDto("task-1", "RUNNING", "backup-2026-11-20", "mediagarrd-2026-11-20.zip", 512L, 1048576L, null, null)); + + mockMvc.perform(post("/api/client/pickup")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pickup-start.json"), JsonCompareMode.STRICT)); + mockMvc.perform(get("/api/client/pickup/progress/task-1")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pickup-progress.json"), JsonCompareMode.STRICT)); + } + + @Test + void pickupIntervalRequestParsesADurationString() throws Exception { + when(stateService.getActiveServer()).thenReturn(SERVER); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(90)); + when(stateService.getKnownServers()).thenReturn(List.of(SERVER, "https://backup.example.net:38471")); + + mockMvc.perform(put("/api/client/pickup-interval").contentType(MediaType.APPLICATION_JSON).content("{\"interval\":\"PT1H30M\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/status.json"), JsonCompareMode.STRICT)); + verify(backupPickupService).updatePickupInterval(Duration.ofMinutes(90)); + } + + @Test + void pairingJson() throws Exception { + when(pairing.pair(eq("123456"), any())).thenReturn(new PairingResultDto(true, "Golden Laptop", null)); + when(pairing.createCode()).thenReturn(new PairingCodeDto("482913", Instant.parse("2026-11-20T10:25:30.500Z"))); + when(pairing.unpair()).thenReturn(new UnpairResultDto(true, null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\",\"name\":\"Golden Laptop\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-result.json"), JsonCompareMode.STRICT)); + mockMvc.perform(post("/api/client/pairing/code")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-code.json"), JsonCompareMode.STRICT)); + mockMvc.perform(delete("/api/client/pairing")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/unpair-result.json"), JsonCompareMode.STRICT)); + } + + @Test + void deferredPairingJson() throws Exception { + when(pairing.pair(eq("123456"), any())).thenReturn(new PairingResultDto(true, "Golden Laptop", "Paired. The server could not be reached to confirm it yet.")); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/pairing-result-deferred.json"), JsonCompareMode.STRICT)); + } + + @Test + void requestBodiesWithUnknownOrMissingFieldsAreAccepted() throws Exception { + when(pairing.pair(eq("123456"), eq(null))).thenReturn(new PairingResultDto(true, null, null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\",\"somethingNew\":1}")) + .andExpect(status().isOk()); + } + + @Test + void authStatusJson() throws Exception { + when(passwords.isConfigured()).thenReturn(true); + when(passwords.isFromEnvironment()).thenReturn(false); + + mockMvc.perform(get("/api/auth/status")) + .andExpect(status().isOk()) + .andExpect(content().json(Fixtures.read("client/auth-status.json"), JsonCompareMode.STRICT)); + } + + @Test + void errorJson() throws Exception { + when(stateService.requireActiveServer()).thenThrow(new InvalidRequestException("No active MediaGarrd server selected")); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isBadRequest()) + .andExpect(content().json(Fixtures.read("client/error-4xx.json"), JsonCompareMode.STRICT)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java index 2106231..b398819 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -18,46 +18,52 @@ import org.junit.jupiter.api.Test; 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.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; +import wellatleastitried.mediagarrdclient.service.NotFoundException; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.DashboardState; import wellatleastitried.mediagarrdclient.dto.HealthSummary; import wellatleastitried.mediagarrdclient.dto.LinkState; +import wellatleastitried.mediagarrdclient.dto.PairingState; 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.BackupRunFailedException; import wellatleastitried.mediagarrdclient.service.BackupRunTimeoutException; import wellatleastitried.mediagarrdclient.service.ServerApiService; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; +import wellatleastitried.mediagarrdclient.service.ServerSelectionService; @WebMvcTest(controllers = ClientController.class) +@Import({TestSession.class, ServerSelectionService.class}) class ClientControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean ClientStateService stateService; - @MockBean + @MockitoBean ServerDiscoveryService discoveryService; - @MockBean + @MockitoBean ServerApiService serverApiService; - @MockBean + @MockitoBean BackupPickupService backupPickupService; - @MockBean + @MockitoBean DashboardService dashboardService; @Test @@ -72,14 +78,14 @@ void mapsABackupRunTimeoutToAGatewayTimeoutWithAnErrorBody() throws Exception { } @Test - void statusEndpointReturnsState() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); + void mapsAFailedBackupRunToAnInternalErrorWithTheReason() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + doThrow(new BackupRunFailedException("Backup of radarr failed: disk is full", null)) + .when(serverApiService).triggerBackup("http://server:8080"); - mockMvc.perform(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.activeServer").value("http://server:8080")); + mockMvc.perform(post("/api/client/backups/run")) + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error").value("Backup of radarr failed: disk is full")); } @Test @@ -95,38 +101,6 @@ void discoverEndpointReturnsOnlyTheServersFoundByTheScan() throws Exception { verify(stateService).updateKnownServers(List.of("http://server:8080")); } - @Test - void listBackupsReturnsServerData() throws Exception { - when(stateService.requireActiveServer()).thenReturn("http://server:8080"); - when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); - - mockMvc.perform(get("/api/client/backups")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value("id")); - } - - @Test - void setServerEndpointAcceptsUpdate() throws Exception { - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(put("/api/client/server") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"serverUrl\":\"http://server:8080\"}")) - .andExpect(status().isOk()); - } - - @Test - void pickupEndpointStartsTask() throws Exception { - when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "id", "file.zip", 10L)); - - mockMvc.perform(post("/api/client/pickup")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.taskId").value("task-1")) - .andExpect(jsonPath("$.backupId").value("id")); - } - @Test void statusHasNoNetworkSideEffect() throws Exception { mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); @@ -142,7 +116,8 @@ void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws E LinkState.DEGRADED, true, new HealthSummary(Duration.ofHours(6), 5), - new VersionsDto(null, null))); + new VersionsDto(null, null), + PairingState.PAIRED)); mockMvc.perform(get("/api/client/dashboard")) .andExpect(status().isOk()) @@ -158,12 +133,35 @@ void dashboardEndpointReturnsTheStoredStateWithoutContactingTheServer() throws E @Test void normalizesSelectedServerUrls() throws Exception { + when(discoveryService.isMediaGarrdServer("http://server:8080")).thenReturn(true); mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\" http://server:8080/ \"}")) .andExpect(status().isOk()); verify(stateService).setActiveServer("http://server:8080"); } + @Test + void refusesAServerUrlThatIsNotAMediaGarrdServer() throws Exception { + when(discoveryService.isMediaGarrdServer("http://intranet-printer:631")).thenReturn(false); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"http://intranet-printer:631\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No MediaGarrd server found at http://intranet-printer:631")); + + verify(stateService, never()).setActiveServer(any()); + } + + @Test + void doesNotProbeAServerThatIsAlreadyKnown() throws Exception { + when(stateService.isKnownServer("http://server:8080")).thenReturn(true); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"http://server:8080\"}")) + .andExpect(status().isOk()); + + verify(stateService).setActiveServer("http://server:8080"); + verify(discoveryService, never()).isMediaGarrdServer(any(String.class)); + } + @Test void rejectsInvalidServerSelections() throws Exception { mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"ftp://server\"}")) @@ -192,16 +190,39 @@ void reportsWhenNoServerAnswersAtTheGivenAddress() throws Exception { @Test void rejectsInvalidPickupIntervals() throws Exception { - when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new IllegalArgumentException("Pickup interval must be a positive duration")); + when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new InvalidRequestException("Pickup interval must be a positive duration")); mockMvc.perform(json(put("/api/client/pickup-interval"), "{\"interval\":\"PT0S\"}")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error").value("Pickup interval must be a positive duration")); } + @Test + void pickingUpASpecificBackupStartsATaskForThatId() throws Exception { + when(backupPickupService.startPickupByIdTask("b1")).thenReturn(new PickupStartDto("task-1", "b1", "b1-media-backup.zip", 10L)); + + mockMvc.perform(post("/api/client/pickup/b1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("task-1")) + .andExpect(jsonPath("$.backupId").value("b1")) + .andExpect(jsonPath("$.fileName").value("b1-media-backup.zip")); + + verify(backupPickupService).startPickupByIdTask("b1"); + verify(backupPickupService, never()).startPickupLatestTask(); + } + + @Test + void pickingUpAnUnknownBackupIsNotFound() throws Exception { + when(backupPickupService.startPickupByIdTask("gone")).thenThrow(new NotFoundException("Backup not found: gone")); + + mockMvc.perform(post("/api/client/pickup/gone")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Backup not found: gone")); + } + @Test void unknownPickupTasksAreNotFound() throws Exception { - when(backupPickupService.pickupProgress("gone")).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + when(backupPickupService.pickupProgress("gone")).thenThrow(new NotFoundException("Pickup task not found: gone")); mockMvc.perform(get("/api/client/pickup/progress/gone")) .andExpect(status().isNotFound()) diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java similarity index 81% rename from src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java rename to src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java index c511d84..670ef83 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientEventBroadcasterTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventBroadcasterTest.java @@ -1,8 +1,7 @@ -package wellatleastitried.mediagarrdclient.service; +package wellatleastitried.mediagarrdclient.api; 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; @@ -11,10 +10,8 @@ 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; @@ -22,54 +19,15 @@ 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; +import wellatleastitried.mediagarrdclient.service.ClientEvent; + @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) { @@ -140,24 +98,43 @@ private static RecordingEmitter subscribe(ClientEventBroadcaster broadcaster) { } @Test - void sendsTheInitialEventsFirstAndTellsTheBrowserHowLongToWaitBeforeReconnecting() throws Exception { + void endingASessionClosesOnlyItsSubscribers() throws Exception { ClientEventBroadcaster broadcaster = broadcaster(); + RecordingEmitter ending = (RecordingEmitter) broadcaster.subscribe("session-a", SNAPSHOT).orElseThrow(); + RecordingEmitter staying = (RecordingEmitter) broadcaster.subscribe("session-b", SNAPSHOT).orElseThrow(); + ending.next(); + staying.next(); - RecordingEmitter emitter = subscribe(broadcaster); + broadcaster.endSession("session-a"); - assertEquals("retry:5000\nevent:snapshot\ndata:{\"link\":\"DOWN\"}\n\n", emitter.next()); - assertNull(emitter.sent.poll(200, TimeUnit.MILLISECONDS)); + assertTrue(ending.completed.await(5, TimeUnit.SECONDS)); + assertEquals(1, broadcaster.subscriberCount()); + broadcaster.publish("state", "{}"); + assertTrue(staying.next().contains("event:state")); } @Test - void theReconnectHintIsSentOnlyOnce() throws Exception { - ClientEventBroadcaster broadcaster = broadcaster(); - RecordingEmitter emitter = subscribe(broadcaster); + void aSubscriberWhoseSessionExpiredIsClosedAtTheNextPing() throws Exception { + java.util.concurrent.atomic.AtomicBoolean active = new java.util.concurrent.atomic.AtomicBoolean(true); + ClientEventBroadcaster broadcaster = new ClientEventBroadcaster(Duration.ofMillis(20), 32, 64, Duration.ofMinutes(10), Duration.ofMinutes(5), threadFactory, + RecordingEmitter::new, key -> active.get()); + broadcasters.add(broadcaster); + RecordingEmitter emitter = (RecordingEmitter) broadcaster.subscribe("session-a", SNAPSHOT).orElseThrow(); emitter.next(); - broadcaster.publish("run-started", "{\"running\":true}"); + active.set(false); - assertEquals("event:run-started\ndata:{\"running\":true}\n\n", emitter.next()); + assertTrue(emitter.completed.await(5, TimeUnit.SECONDS)); + } + + @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 diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java index f19e41e..2097831 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientEventsControllerTest.java @@ -1,5 +1,6 @@ package wellatleastitried.mediagarrdclient.api; +import static org.mockito.ArgumentMatchers.any; 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; @@ -9,40 +10,53 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; +import java.util.List; import java.util.Optional; +import java.util.function.Function; +import org.junit.jupiter.api.BeforeEach; 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.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; 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.ClientEvent; import wellatleastitried.mediagarrdclient.service.DashboardService; @WebMvcTest(controllers = ClientEventsController.class) +@Import(TestSession.class) @Timeout(20) class ClientEventsControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean DashboardService dashboard; + @MockitoBean + ClientEventBroadcaster broadcaster; + + @BeforeEach + void dashboardRegistersTheSubscriber() { + when(dashboard.subscribe(any())).thenAnswer(invocation -> invocation., Optional>>getArgument(0).apply(List.of())); + } + @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)); + when(broadcaster.subscribe(any(), any())).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")); @@ -51,7 +65,7 @@ void opensAnUnbufferedEventStream() throws Exception { @Test void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { - when(dashboard.subscribe()).thenReturn(Optional.empty()); + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.empty()); mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(status().isServiceUnavailable()) @@ -62,7 +76,7 @@ void answers503WhenTooManyBrowsersAreSubscribed() throws Exception { void aBrowserThatWentAwayEndsTheStreamWithoutAnError() throws Exception { SseEmitter emitter = new SseEmitter(60_000L); emitter.send(SseEmitter.event().name("link").data("{}")); - when(dashboard.subscribe()).thenReturn(Optional.of(emitter)); + when(broadcaster.subscribe(any(), any())).thenReturn(Optional.of(emitter)); MvcResult started = mockMvc.perform(get("/api/client/events").accept(MediaType.TEXT_EVENT_STREAM)) .andExpect(request().asyncStarted()) .andReturn(); diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java new file mode 100644 index 0000000..ab0b189 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/CsrfCheckTest.java @@ -0,0 +1,94 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +class CsrfCheckTest { + + private static MockHttpServletRequest post() { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/client/backups/run"); + request.addHeader("Host", "192.168.1.5:8081"); + return request; + } + + @Test + void safeMethodsAreAlwaysAllowed() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/client/status"); + request.addHeader("Origin", "http://evil.example.com"); + request.addHeader("Sec-Fetch-Site", "cross-site"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void aSameOriginFetchMetadataHeaderIsAccepted() { + MockHttpServletRequest request = post(); + request.addHeader("Sec-Fetch-Site", "same-origin"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void anyOtherFetchMetadataValueIsRefusedEvenWithAMatchingOrigin() { + for (String site : new String[] {"same-site", "cross-site", "none"}) { + MockHttpServletRequest request = post(); + request.addHeader("Sec-Fetch-Site", site); + request.addHeader("Origin", "http://192.168.1.5:8081"); + + assertFalse(CsrfCheck.allows(request), site); + } + } + + @Test + void anOriginMatchingTheHostIsAcceptedWithoutFetchMetadata() { + MockHttpServletRequest request = post(); + request.addHeader("Origin", "http://192.168.1.5:8081"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void anotherPortOnTheSameHostIsAnotherOrigin() { + MockHttpServletRequest request = post(); + request.addHeader("Origin", "http://192.168.1.5:8096"); + + assertFalse(CsrfCheck.allows(request)); + } + + @Test + void aForeignOriginAndTheNullOriginAreRefused() { + MockHttpServletRequest foreign = post(); + foreign.addHeader("Origin", "https://evil.example.com"); + MockHttpServletRequest opaque = post(); + opaque.addHeader("Origin", "null"); + + assertFalse(CsrfCheck.allows(foreign)); + assertFalse(CsrfCheck.allows(opaque)); + } + + @Test + void aProxyThatKeepsTheOriginalHostInAForwardedHeaderIsSupported() { + MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/api/client/server"); + request.addHeader("Host", "client:8081"); + request.addHeader("X-Forwarded-Host", "garrd.example.com"); + request.addHeader("Origin", "https://garrd.example.com"); + + assertTrue(CsrfCheck.allows(request)); + } + + @Test + void requestsWithoutBrowserHeadersNeedTheCustomHeader() { + MockHttpServletRequest without = post(); + MockHttpServletRequest with = post(); + with.addHeader("X-MediaGarrd-Request", "1"); + MockHttpServletRequest wrong = post(); + wrong.addHeader("X-MediaGarrd-Request", "0"); + + assertFalse(CsrfCheck.allows(without)); + assertTrue(CsrfCheck.allows(with)); + assertFalse(CsrfCheck.allows(wrong)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java new file mode 100644 index 0000000..e7fadbe --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/FirstVisitPasswordFullContextTest.java @@ -0,0 +1,108 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import jakarta.servlet.http.Cookie; + +@SpringBootTest +@org.springframework.context.annotation.Import(wellatleastitried.mediagarrdclient.api.TestCsrfHeader.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class FirstVisitPasswordFullContextTest { + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @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"); + registry.add("mediagarrd.client.password", () -> ""); + } + + private static String body(String password) { + return "{\"password\":\"" + password + "\"}"; + } + + @Test + @Order(1) + void withoutAPasswordTheDashboardOffersToSetOneAndLoginIsRefused() throws Exception { + mockMvc.perform(get("/api/auth/status")) + .andExpect(jsonPath("$.passwordSet").value(false)) + .andExpect(jsonPath("$.passwordFromEnvironment").value(false)) + .andExpect(jsonPath("$.authenticated").value(false)); + mockMvc.perform(get("/api/client/status")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("anything at all"))) + .andExpect(status().isConflict()); + } + + @Test + @Order(2) + void aCrossSiteRequestCannotSetThePasswordAndAShortOneIsRefused() throws Exception { + mockMvc.perform(post("/api/auth/set-password").header("Origin", "http://evil.example.com").header("Host", "client.local:8081") + .contentType(MediaType.APPLICATION_JSON).content(body("long enough password"))) + .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("short"))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").exists()); + mockMvc.perform(get("/api/auth/status")).andExpect(jsonPath("$.passwordSet").value(false)); + } + + @Test + @Order(3) + void theFirstVisitorSetsThePasswordAndIsSignedIn() throws Exception { + MvcResult result = mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("my first password"))) + .andExpect(status().isOk()) + .andReturn(); + Cookie cookie = result.getResponse().getCookie("mg_session"); + + mockMvc.perform(get("/api/client/status").cookie(cookie)).andExpect(status().isOk()); + Path file = dataDir.resolve("password.json"); + assertTrue(Files.exists(file)); + assertFalse(Files.readString(file).contains("my first password")); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + } + + @Test + @Order(4) + void theSecondVisitorCannotReplaceThePasswordButCanLogInWithIt() throws Exception { + mockMvc.perform(post("/api/auth/set-password").contentType(MediaType.APPLICATION_JSON).content(body("an attacker password"))) + .andExpect(status().isConflict()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("an attacker password"))) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON).content(body("my first password"))) + .andExpect(status().isOk()); + mockMvc.perform(get("/api/auth/status")).andExpect(jsonPath("$.passwordSet").value(true)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java new file mode 100644 index 0000000..efca189 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/PairingControllerTest.java @@ -0,0 +1,76 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Instant; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; + +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.PairingResultDto; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; +import wellatleastitried.mediagarrdclient.service.ClientPairingService; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; + +@WebMvcTest(controllers = PairingController.class) +@Import(TestSession.class) +class PairingControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientPairingService pairing; + + @Test + void pairsAndNeverReturnsAToken() throws Exception { + when(pairing.pair("123456", null)).thenReturn(new PairingResultDto(true, "MediaGarrd Client", null)); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"123456\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.paired").value(true)) + .andExpect(jsonPath("$.name").value("MediaGarrd Client")) + .andExpect(jsonPath("$.token").doesNotExist()); + } + + @Test + void passesOnWhyTheServerRefusedThePairing() throws Exception { + when(pairing.pair("000000", null)).thenThrow(new InvalidRequestException("Invalid PIN")); + + mockMvc.perform(post("/api/client/pairing").contentType(MediaType.APPLICATION_JSON).content("{\"pin\":\"000000\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Invalid PIN")); + } + + @Test + void aRejectedTokenIsABadGatewayWithThePairingMarker() throws Exception { + when(pairing.createCode()).thenThrow(new PairingRequiredException("The server rejected this client's token, pair it again")); + + mockMvc.perform(post("/api/client/pairing/code")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.pairing").value("required")) + .andExpect(jsonPath("$.error").exists()); + } + + @Test + void unpairsAndSaysWhetherTheServerWasTold() throws Exception { + when(pairing.unpair()).thenReturn(new UnpairResultDto(false, "The server could not be told")); + + mockMvc.perform(delete("/api/client/pairing")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.serverRevoked").value(false)) + .andExpect(jsonPath("$.warning").value("The server could not be told")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java b/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java new file mode 100644 index 0000000..e4f3144 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/RecordingEmitter.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +public class RecordingEmitter extends SseEmitter { + + public final BlockingQueue sent = new LinkedBlockingQueue<>(); + public final CountDownLatch completed = new CountDownLatch(1); + + public 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(); + } + + public String next() throws InterruptedException { + String event = sent.poll(5, TimeUnit.SECONDS); + assertNotNull(event, "timed out waiting for an event"); + return event; + } + + public String nextContaining(String marker) throws InterruptedException { + while (true) { + String event = next(); + if (event.contains(marker)) { + return event; + } + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java new file mode 100644 index 0000000..8314d0e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/RunningServerTest.java @@ -0,0 +1,163 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +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.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Timeout(60) +class RunningServerTest { + + @TempDir + static Path dataDir; + + @LocalServerPort + int port; + + private final HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).connectTimeout(Duration.ofSeconds(5)).build(); + + @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"); + registry.add("mediagarrd.client.password", () -> ""); + } + + private URI uri(String path) { + return URI.create("http://127.0.0.1:" + port + path); + } + + private HttpRequest.Builder request(String path) { + return HttpRequest.newBuilder(uri(path)).header("X-MediaGarrd-Request", "1").timeout(Duration.ofSeconds(20)); + } + + private HttpResponse send(HttpRequest request) throws Exception { + return client.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private String signIn() throws Exception { + String body = "{\"password\":\"a long enough password\"}"; + HttpResponse response = send(request("/api/auth/set-password").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)).build()); + if (response.statusCode() == 409) { + response = send(request("/api/auth/login").header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)).build()); + } + assertEquals(200, response.statusCode()); + String cookie = response.headers().firstValue("Set-Cookie").orElseThrow(); + return cookie.substring(0, cookie.indexOf(';')); + } + + @Test + void servesSecurityHeadersOnPagesAndApiResponses() throws Exception { + for (String path : new String[] {"/", "/index.html", "/js/main.js", "/api/auth/status", "/api/client/status", "/nothing-here"}) { + HttpResponse response = send(request(path).GET().build()); + + assertEquals(SecurityHeadersFilter.CONTENT_SECURITY_POLICY, response.headers().firstValue("Content-Security-Policy").orElse(null), path); + assertEquals("nosniff", response.headers().firstValue("X-Content-Type-Options").orElse(null), path); + assertEquals("no-referrer", response.headers().firstValue("Referrer-Policy").orElse(null), path); + assertEquals("DENY", response.headers().firstValue("X-Frame-Options").orElse(null), path); + if (path.startsWith("/api/")) { + assertEquals(java.util.List.of("no-store"), response.headers().allValues("Cache-Control"), path); + } + } + } + + @Test + void anUnknownApiPathAnswersWithTheErrorShape() throws Exception { + String cookie = signIn(); + + HttpResponse response = send(request("/api/client/no-such-endpoint").header("Cookie", cookie).GET().build()); + + assertTrue(response.statusCode() >= 400 && response.statusCode() < 500); + assertTrue(response.body().contains("\"error\"")); + } + + @Test + void refusesARequestBodyOverTheCapWhetherItIsDeclaredOrChunked() throws Exception { + byte[] oversized = ("{\"password\":\"" + "x".repeat((int) BodyLimitFilter.MAX_BODY_BYTES + 10) + "\"}").getBytes(StandardCharsets.UTF_8); + + HttpResponse declared = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofByteArray(oversized)).build()); + HttpResponse chunked = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(oversized))).build()); + + assertEquals(413, declared.statusCode()); + assertEquals("{\"error\":\"Request body is too large\"}", declared.body()); + assertEquals(413, chunked.statusCode()); + assertEquals("{\"error\":\"Request body is too large\"}", chunked.body()); + } + + @Test + void aChunkedBodyWithinTheCapStillWorks() throws Exception { + signIn(); + byte[] small = "{\"password\":\"wrong password\"}".getBytes(StandardCharsets.UTF_8); + + HttpResponse response = send(request("/api/auth/login").header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(small))).build()); + + assertEquals(401, response.statusCode()); + assertEquals("{\"error\":\"Incorrect password\"}", response.body()); + } + + @Test + void theEventStreamNeedsASessionDeliversASnapshotAndEndsWhenTheSessionDoes() throws Exception { + assertEquals(401, send(request("/api/client/events").header("Accept", "text/event-stream").GET().build()).statusCode()); + String cookie = signIn(); + + HttpResponse stream = client.send(request("/api/client/events").header("Cookie", cookie).header("Accept", "text/event-stream").GET().build(), + HttpResponse.BodyHandlers.ofInputStream()); + + assertEquals(200, stream.statusCode()); + assertTrue(stream.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream")); + assertEquals(java.util.List.of("no-store"), stream.headers().allValues("Cache-Control")); + BufferedReader reader = new BufferedReader(new InputStreamReader(stream.body(), StandardCharsets.UTF_8)); + String line; + String event = null; + while ((line = reader.readLine()) != null && event == null) { + if (line.startsWith("event:")) { + event = line; + } + } + assertEquals("event:snapshot", event); + + CompletableFuture ended = CompletableFuture.supplyAsync(() -> { + try { + while (reader.readLine() != null) { + continue; + } + return true; + } catch (java.io.IOException e) { + return true; + } + }); + HttpResponse logout = send(request("/api/auth/logout").header("Cookie", cookie).POST(HttpRequest.BodyPublishers.noBody()).build()); + assertEquals(204, logout.statusCode()); + + assertTrue(ended.get(10, TimeUnit.SECONDS)); + assertNotNull(logout.headers().firstValue("Set-Cookie").orElse(null)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java index de33936..7f8e313 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java @@ -18,14 +18,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; 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.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.server.ResponseStatusException; +import wellatleastitried.mediagarrdclient.service.InvalidRequestException; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; @@ -34,6 +35,7 @@ import wellatleastitried.mediagarrdclient.service.ServerApiService; @WebMvcTest(controllers = ServerConfigController.class) +@Import(TestSession.class) class ServerConfigControllerTest { private static final String SERVER = "http://server:8080"; @@ -45,10 +47,10 @@ class ServerConfigControllerTest { @Autowired MockMvc mockMvc; - @MockBean + @MockitoBean ClientStateService stateService; - @MockBean + @MockitoBean ServerApiService serverApiService; @BeforeEach @@ -57,45 +59,45 @@ void setUp() { } @Test - void returnsServerConfig() throws Exception { - when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 4, Duration.ofHours(6))); + void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { + when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); - mockMvc.perform(get("/api/client/server-config")) + mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.backupLocation").value("/backups")) - .andExpect(jsonPath("$.retentionCount").value(4)) .andExpect(jsonPath("$.backupInterval").value("PT6H")); + + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); } @Test - void updatesConfigAndScheduleTogether() throws Exception { - when(serverApiService.updateServerConfig(SERVER, "/new", 3)).thenReturn(new ServerConfigDto("/new", 3, Duration.ofHours(6))); - when(serverApiService.updateServerSchedule(SERVER, Duration.ofMinutes(90))) - .thenReturn(new ServerStatusDto(true, false, 3, Duration.ofMinutes(90))); - - mockMvc.perform(json(put("/api/client/server-config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 3, \"backupInterval\": \"PT90M\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.backupLocation").value("/new")) - .andExpect(jsonPath("$.retentionCount").value(3)) - .andExpect(jsonPath("$.backupInterval").value("PT1H30M")); + void refusesAnOutOfRangeIntervalBeforeChangingAnything() throws Exception { + for (String interval : List.of("\"PT14M59S\"", "\"PT0S\"", "\"-PT1H\"", "\"PT8761H\"", "899", "31536001")) { + mockMvc.perform(json(put("/api/client/server-config"), + "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": " + interval + "}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Backup interval must be between 15 minutes and 365 days")); + } + + verify(serverApiService, never()).updateServerConfig(anyString(), any(), any()); + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); } @Test - void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { - when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); - - mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.backupInterval").value("PT6H")); - - verify(serverApiService, never()).updateServerSchedule(anyString(), any()); + void acceptsTheIntervalBounds() throws Exception { + when(serverApiService.updateServerConfig(SERVER, "/backups", 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + for (String interval : List.of("\"PT15M\"", "\"PT8760H\"", "900", "31536000")) { + when(serverApiService.updateServerSchedule(anyString(), any())).thenReturn(new ServerStatusDto(true, false, 5, Duration.ofMinutes(15))); + mockMvc.perform(json(put("/api/client/server-config"), + "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": " + interval + "}")) + .andExpect(status().isOk()); + } } @Test void forwardsServiceChanges() throws Exception { when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); - when(serverApiService.updateService(SERVER, "old name", RADARR)).thenReturn(RADARR); + when(serverApiService.updateService(SERVER, "radarr-4k", RADARR)).thenReturn(RADARR); mockMvc.perform(get("/api/client/services")) .andExpect(status().isOk()) @@ -104,7 +106,7 @@ void forwardsServiceChanges() throws Exception { mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.name").value("radarr")); - mockMvc.perform(json(put("/api/client/services/old name"), RADARR_JSON)) + mockMvc.perform(json(put("/api/client/services/radarr-4k"), RADARR_JSON)) .andExpect(status().isOk()); mockMvc.perform(delete("/api/client/services/radarr")) .andExpect(status().isNoContent()); @@ -113,15 +115,41 @@ void forwardsServiceChanges() throws Exception { } @Test - void rejectsRequestsWithoutAnActiveServer() throws Exception { - when(stateService.requireActiveServer()) - .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected")); - - mockMvc.perform(get("/api/client/services")) + void refusesServiceNamesThatCouldChangeThePath() throws Exception { + mockMvc.perform(json(put("/api/client/services/%2E%2E"), RADARR_JSON)) + .andExpect(status().isBadRequest()); + mockMvc.perform(json(put("/api/client/services/a%2Fb"), RADARR_JSON)) + .andExpect(status().isBadRequest()); + mockMvc.perform(delete("/api/client/services/..%5Cetc")) .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error").value("No active MediaGarrd server selected")); + .andExpect(jsonPath("$.error").exists()); - verify(serverApiService, never()).listServices(anyString()); + verify(serverApiService, never()).updateService(anyString(), anyString(), any()); + verify(serverApiService, never()).removeService(anyString(), anyString()); + } + + @Test + void routineReadsDoNotLogAtInfoButWritesDo() throws Exception { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + root.addAppender(logs); + try { + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); + mockMvc.perform(get("/api/client/server-config")).andExpect(status().isOk()); + mockMvc.perform(get("/api/client/services")).andExpect(status().isOk()); + long infoAfterReads = logs.list.stream().filter(event -> event.getLevel().toInt() >= ch.qos.logback.classic.Level.INFO_INT && event.getLoggerName().endsWith("ServerConfigController")).count(); + + when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); + mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)).andExpect(status().isCreated()); + long infoAfterWrite = logs.list.stream().filter(event -> event.getLevel().toInt() >= ch.qos.logback.classic.Level.INFO_INT && event.getLoggerName().endsWith("ServerConfigController")).count(); + + org.junit.jupiter.api.Assertions.assertEquals(0, infoAfterReads); + org.junit.jupiter.api.Assertions.assertEquals(1, infoAfterWrite); + } finally { + root.detachAppender(logs); + } } @Test diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java b/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java new file mode 100644 index 0000000..800ae18 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/TestCsrfHeader.java @@ -0,0 +1,16 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcBuilderCustomizer; +import org.springframework.context.annotation.Bean; + +@TestConfiguration +public class TestCsrfHeader { + + @Bean + MockMvcBuilderCustomizer csrfHeader() { + return builder -> builder.defaultRequest(get("/").header(CsrfCheck.HEADER, "1")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java b/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java new file mode 100644 index 0000000..d82922e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/TestSession.java @@ -0,0 +1,25 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.MockMvcBuilderCustomizer; +import org.springframework.context.annotation.Bean; + +import jakarta.servlet.http.Cookie; +import wellatleastitried.mediagarrdclient.service.SessionService; + +@TestConfiguration +public class TestSession { + + @Bean + SessionService sessionService() { + return new SessionService(); + } + + @Bean + MockMvcBuilderCustomizer signedInRequests(SessionService sessions) { + Cookie cookie = new Cookie(SessionGate.COOKIE, sessions.create()); + return builder -> builder.defaultRequest(get("/").cookie(cookie).header(CsrfCheck.HEADER, "1")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java new file mode 100644 index 0000000..e37e6d0 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/WebhookControllerTest.java @@ -0,0 +1,128 @@ +package wellatleastitried.mediagarrdclient.api; + +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; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; + +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.PairingRequiredException; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@WebMvcTest(controllers = WebhookController.class) +@Import(TestSession.class) +class WebhookControllerTest { + + private static final String SERVER = "http://server:8080"; + + @Autowired + MockMvc mockMvc; + + @MockitoBean + ClientStateService stateService; + + @MockitoBean + ServerApiService serverApiService; + + @BeforeEach + void setUp() { + when(stateService.requireActiveServer()).thenReturn(SERVER); + } + + @Test + void forwardsTheStatusReadToTheActiveServer() throws Exception { + when(serverApiService.webhook(SERVER)).thenReturn(new WebhookStatusDto(true, "https://hooks.slack.com")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(true)) + .andExpect(jsonPath("$.target").value("https://hooks.slack.com")); + } + + @Test + void forwardsASetAndAClear() throws Exception { + when(serverApiService.updateWebhook(SERVER, "https://hooks.slack.com/services/T/B/X")).thenReturn(new WebhookStatusDto(true, "https://hooks.slack.com")); + when(serverApiService.updateWebhook(SERVER, "")).thenReturn(new WebhookStatusDto(false, null)); + + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"https://hooks.slack.com/services/T/B/X\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(true)); + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.configured").value(false)); + } + + @Test + void forwardsTheTestAndItsResult() throws Exception { + when(serverApiService.testWebhook(SERVER)).thenReturn(new WebhookTestDto(true, 204, null)); + + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.delivered").value(true)) + .andExpect(jsonPath("$.status").value(204)); + } + + @Test + void passesTheServersValidationMessageThrough() throws Exception { + when(serverApiService.updateWebhook(SERVER, "ftp://x")).thenThrow(rejected(HttpStatus.BAD_REQUEST, new HttpHeaders(), "Webhook URL must use http or https")); + + mockMvc.perform(put("/api/client/notifications/webhook").contentType(MediaType.APPLICATION_JSON).content("{\"url\":\"ftp://x\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Webhook URL must use http or https")); + } + + @Test + void passesTheTestCooldownAndItsRetryAfterThrough() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.RETRY_AFTER, "8"); + when(serverApiService.testWebhook(SERVER)).thenThrow(rejected(HttpStatus.TOO_MANY_REQUESTS, headers, "Wait 8 seconds before sending another test")); + + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isTooManyRequests()) + .andExpect(header().string(HttpHeaders.RETRY_AFTER, "8")) + .andExpect(jsonPath("$.error").value("Wait 8 seconds before sending another test")); + } + + @Test + void reportsAnUnreachableServerAndAMissingPairing() throws Exception { + when(serverApiService.webhook(SERVER)).thenThrow(new ResourceAccessException("Connection refused")); + when(serverApiService.testWebhook(SERVER)).thenThrow(new PairingRequiredException("Pair with the server first")); + + mockMvc.perform(get("/api/client/notifications/webhook")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.error").value("MediaGarrd server is unreachable")); + mockMvc.perform(post("/api/client/notifications/webhook/test")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.pairing").value("required")); + } + + @Test + void theUpdateRequestDoesNotPrintTheUrl() { + org.junit.jupiter.api.Assertions.assertFalse( + new wellatleastitried.mediagarrdclient.dto.WebhookUpdateRequest("https://discord.com/api/webhooks/1/SECRETTOKEN").toString().contains("SECRETTOKEN")); + } + + private static HttpClientErrorException rejected(HttpStatus status, HttpHeaders headers, String message) { + HttpClientErrorException e = HttpClientErrorException.create(status, status.getReasonPhrase(), headers, new byte[0], java.nio.charset.StandardCharsets.UTF_8); + e.setBodyConvertFunction(type -> new ApiExceptionHandler.ServerError(message)); + return e; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java b/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java new file mode 100644 index 0000000..0efa996 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/golden/Fixtures.java @@ -0,0 +1,23 @@ +package wellatleastitried.mediagarrdclient.golden; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +public final class Fixtures { + + private Fixtures() { + } + + public static String read(String name) { + try (InputStream in = Fixtures.class.getResourceAsStream("/golden/" + name)) { + if (in == null) { + throw new IllegalArgumentException("Missing fixture " + name); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java index 4c39aa4..916225c 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java @@ -2,11 +2,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,22 +16,19 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneOffset; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.http.HttpStatus; -import org.springframework.web.server.ResponseStatusException; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.BackupDto; import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; import wellatleastitried.mediagarrdclient.dto.PickupStartDto; @@ -50,9 +49,11 @@ class BackupPickupServiceTest { @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + MediaGarrdProperties configuration = new MediaGarrdProperties(); configuration.setDownloadDirectory(downloads.toString()); when(state.requireActiveServer()).thenReturn(SERVER); + when(state.getActiveServer()).thenReturn(SERVER); + when(state.hasPairing(SERVER)).thenReturn(true); when(state.getPickupInterval()).thenReturn(Duration.ofHours(1)); when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); pickup = new BackupPickupService(configuration, state, api, clock); @@ -103,7 +104,7 @@ void reusesAnExistingDownload() throws Exception { @Test void reportsDownloadFailures() throws Exception { - when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("disk full")); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("disk full")); PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); @@ -119,22 +120,80 @@ void forgetsFinishedTasksAfterTheRetentionPeriod() throws Exception { clock.advance(BackupPickupService.FINISHED_TASK_RETENTION.plusSeconds(1)); pickup.startPickupByIdTask("b1"); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress(taskId)); + assertThrows(NotFoundException.class, () -> pickup.pickupProgress(taskId)); } @Test void rejectsUnknownBackupsAndTasks() { - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupByIdTask("missing")); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress("missing")); + assertThrows(NotFoundException.class, () -> pickup.startPickupByIdTask("missing")); + assertThrows(NotFoundException.class, () -> pickup.pickupProgress("missing")); when(api.listBackups(SERVER)).thenReturn(List.of()); - assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupLatestTask()); + assertThrows(NotFoundException.class, () -> pickup.startPickupLatestTask()); } @Test void refusesFileNamesThatLeaveTheDownloadDirectory() { when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); - assertThrows(IllegalArgumentException.class, () -> pickup.startPickupLatestTask()); + assertThrows(InvalidRequestException.class, () -> pickup.startPickupLatestTask()); + } + + @Test + void aRefusedFileNameLeavesNoStuckTaskBehind() { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); + + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void aFailedDownloadReportsAGenericMessageInsteadOfItsDetails() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("cannot write /var/lib/mediagarrd/downloads/b2.part")); + + PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertEquals(BackupPickupService.GENERIC_FAILURE, progress.error()); + } + + @Test + void scheduledPickupDoesNotBlockTheSchedulerThread() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicBoolean downloadFinished = new AtomicBoolean(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(10, TimeUnit.SECONDS); + downloadFinished.set(true); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + clock.advance(Duration.ofHours(2)); + + pickup.scheduledPickup(); + boolean returnedWhileDownloading = !downloadFinished.get(); + assertTrue(started.await(5, TimeUnit.SECONDS)); + pickup.scheduledPickup(); + clock.advance(Duration.ofHours(2)); + pickup.scheduledPickup(); + release.countDown(); + + assertTrue(returnedWhileDownloading, "the scheduler thread waited for the download"); + verify(api, timeout(5000).times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void scheduledPickupNeverDeletesAUsersCopyOfTheLatestArchive() throws IOException { + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[4]); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertEquals(List.of("b2-media-backup.zip"), fileNames()); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); } @Test @@ -148,11 +207,68 @@ void scheduledPickupKeepsOnlyTheLatestAutomaticDownload() throws IOException { }); clock.advance(Duration.ofHours(2)); - pickup.scheduledPickup(); + pickup.runScheduledPickup(); assertEquals(List.of("b2-media-backup-AD.zip", "b2-media-backup.zip"), fileNames()); } + @Test + void scheduledPickupRemovesOnlyOlderListedAutomaticDownloads() throws IOException { + BackupDto older = new BackupDto("b0", "b0-media-backup.zip", 4, Instant.EPOCH); + BackupDto newer = new BackupDto("b3", "b3-media-backup.zip", 4, Instant.EPOCH); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER, older)); + Files.write(downloads.resolve("b1-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b0-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b3-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("other-server-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("notes-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + Files.createDirectory(downloads.resolve("b0-media-backup-AD.zip.dir")); + Path outside = Files.write(downloads.resolve("outside.bin"), new byte[4]); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertEquals(List.of("b0-media-backup-AD.zip.dir", "b1-media-backup.zip", "b2-media-backup-AD.zip", "b3-media-backup-AD.zip", + "notes-AD.zip", "other-server-media-backup-AD.zip", "outside.bin"), fileNames()); + assertTrue(Files.exists(outside)); + } + + @Test + void scheduledPickupDoesNotFollowSymlinksWhenRemovingSupersededDownloads() throws IOException { + Path target = Files.write(downloads.resolve("target.bin"), new byte[4]); + Files.createSymbolicLink(downloads.resolve("b1-media-backup-AD.zip"), target); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path destination = invocation.getArgument(2); + Files.write(destination, new byte[4]); + return destination; + }); + + clock.advance(Duration.ofHours(2)); + pickup.runScheduledPickup(); + + assertTrue(Files.isSymbolicLink(downloads.resolve("b1-media-backup-AD.zip"))); + assertTrue(Files.exists(target)); + } + + @Test + void refusesArchiveNamesThatAreNotZipFilesBeforeDownloading() { + for (String name : List.of("evil.part", "evil.tar", "evil.zip.part", "evil")) { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", name, 4, Instant.EPOCH))); + + assertThrows(InvalidRequestException.class, () -> pickup.startPickupLatestTask()); + assertThrows(InvalidRequestException.class, () -> pickup.startPickupByIdTask("evil")); + pickup.runScheduledPickup(); + } + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + private PickupProgressDto awaitFinished(String taskId) throws InterruptedException { for (int attempt = 0; attempt < 200; attempt++) { PickupProgressDto progress = pickup.pickupProgress(taskId); @@ -169,31 +285,4 @@ private List fileNames() throws IOException { return files.map(path -> path.getFileName().toString()).sorted().toList(); } } - - private static void assertStatus(HttpStatus status, Runnable action) { - assertEquals(status, assertThrows(ResponseStatusException.class, action::run).getStatusCode()); - } - - private static final class MutableClock extends Clock { - private Instant now = Instant.parse("2026-10-26T00:00:00Z"); - - void advance(Duration duration) { - now = now.plus(duration); - } - - @Override - public Instant instant() { - return now; - } - - @Override - public java.time.ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(java.time.ZoneId zone) { - return this; - } - } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java new file mode 100644 index 0000000..a37aaf6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientPairingServiceTest.java @@ -0,0 +1,360 @@ +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 static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.UnpairResultDto; + +class ClientPairingServiceTest { + + private static final String SERVER = "http://server:38471"; + + @TempDir + Path tempDir; + + private ClientStateService state; + private ServerApiService api; + private ClientPairingService pairing; + private final List pauses = new ArrayList<>(); + + @BeforeEach + void setUp() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + state = new ClientStateService(configuration, JsonMapper.builder().build()); + state.setActiveServer(SERVER); + api = mock(ServerApiService.class); + pauses.clear(); + pairing = new ClientPairingService(state, api, pauses::add); + } + + @Test + void storesTheTokenForTheActiveServerAndReturnsNoToken() { + when(api.pair(SERVER, "123456", "MediaGarrd Client")).thenReturn(new StoredPairing("tok", "id1", "MediaGarrd Client")); + + var result = pairing.pair(" 123456 ", null); + + assertTrue(result.paired()); + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + assertFalse(result.toString().contains("tok")); + } + + @Test + void refusesABlankCredentialWithoutCallingTheServer() { + assertThrows(InvalidRequestException.class, () -> pairing.pair(" ", null)); + verify(api, never()).pair(anyString(), anyString(), anyString()); + } + + @Test + void refusesAnOverlongCredentialOrNameWithoutCallingTheServer() { + assertThrows(InvalidRequestException.class, () -> pairing.pair("1".repeat(ClientPairingService.MAX_CREDENTIAL_LENGTH + 1), null)); + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "n".repeat(ClientPairingService.MAX_NAME_LENGTH + 1))); + verify(api, never()).pair(anyString(), anyString(), anyString()); + } + + @Test + void refusesToPairAgainWhileTheStoredTokenStillWorks() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + + ConflictException e = assertThrows(ConflictException.class, () -> pairing.pair("123456", "Home")); + + assertEquals(ClientPairingService.ALREADY_PAIRED_MESSAGE, e.getMessage()); + verify(api).confirmPairing(SERVER, "old-tok"); + verify(api, never()).pair(anyString(), anyString(), anyString()); + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void pairsAgainWhenTheServerRefusesTheStoredToken() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new InvalidRequestException("no")).when(api).confirmPairing(SERVER, "old-tok"); + when(api.pair(SERVER, "123456", "Home")).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertNull(result.note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + verify(api, never()).revokeClient(anyString(), anyString()); + } + + @Test + void refusesToPairWhenTheStoredTokenCannotBeProbed() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "old-tok"); + + assertThrows(ResourceAccessException.class, () -> pairing.pair("123456", "Home")); + + verify(api, never()).pair(anyString(), anyString(), anyString()); + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aFailedNewPairingKeepsTheDeadStoredToken() { + state.storePairing(SERVER, new StoredPairing("old-tok", "old-id", "Home")); + doThrow(new InvalidRequestException("no")).when(api).confirmPairing(SERVER, "old-tok"); + when(api.pair(anyString(), anyString(), anyString())).thenThrow(new InvalidRequestException("Invalid PIN")); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("000000", "Home")); + + assertEquals("old-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void unpairingWithoutAStoredIdOrPairingExplainsWhy() { + assertEquals(ClientPairingService.NOT_PAIRED_WARNING, pairing.unpair().warning()); + state.storePairing(SERVER, new StoredPairing("tok", null, "Home")); + + UnpairResultDto result = pairing.unpair(); + + assertFalse(result.serverRevoked()); + assertEquals(ClientPairingService.NO_ID_WARNING, result.warning()); + } + + @Test + void aFailedPairingStoresNothing() { + when(api.pair(anyString(), anyString(), anyString())).thenThrow(new ResourceAccessException("down")); + + assertThrows(ResourceAccessException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingRevokesOnTheServerAndForgetsTheToken() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + + UnpairResultDto result = pairing.unpair(); + + assertTrue(result.serverRevoked()); + assertNull(result.warning()); + verify(api).revokeClient(SERVER, "id1"); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingForgetsTheTokenEvenWhenTheServerIsUnreachable() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + doThrow(new ResourceAccessException("down")).when(api).revokeClient(SERVER, "id1"); + + UnpairResultDto result = pairing.unpair(); + + assertFalse(result.serverRevoked()); + assertEquals(ClientPairingService.UNREVOKED_WARNING, result.warning()); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void unpairingForgetsTheTokenEvenWhenTheServerRejectsIt() { + state.storePairing(SERVER, new StoredPairing("tok", "id1", "Home")); + doThrow(new PairingRequiredException("rejected")).when(api).revokeClient(SERVER, "id1"); + + assertFalse(pairing.unpair().serverRevoked()); + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void storesThePairingBeforeConfirmingIt() { + when(api.pair(SERVER, "123456", "MediaGarrd Client")).thenReturn(new StoredPairing("tok", "id1", "MediaGarrd Client")); + doAnswer(call -> { + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + return null; + }).when(api).confirmPairing(SERVER, "tok"); + + var result = pairing.pair("123456", null); + + assertTrue(result.paired()); + assertNull(result.note()); + verify(api).confirmPairing(SERVER, "tok"); + assertEquals("tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aRefusedConfirmationForgetsTheNewPairing() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new InvalidRequestException("The server did not accept this pairing")).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + verify(api, times(1)).confirmPairing(SERVER, "new-tok"); + assertTrue(pauses.isEmpty()); + } + + @Test + void aPublicOnlyConfirmationForgetsTheNewPairing() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ConfirmationRefusedException("not a confirmation")).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(ConfirmationRefusedException.class, () -> pairing.pair("123456", "Home")); + + assertFalse(state.hasPairing(SERVER)); + } + + @Test + void aRefusedConfirmationDoesNotForgetANewerPairingStoredMeanwhile() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doAnswer(call -> { + state.storePairing(SERVER, new StoredPairing("newer-tok", "newer-id", "Home")); + throw new InvalidRequestException("no"); + }).when(api).confirmPairing(SERVER, "new-tok"); + + assertThrows(InvalidRequestException.class, () -> pairing.pair("123456", "Home")); + + assertEquals("newer-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aServerErrorOnConfirmationKeepsTheTokenAndReturnsTheNote() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new UpstreamResponseException("status 500")).when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, result.note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + verify(api, times(1)).confirmPairing(SERVER, "new-tok"); + } + + @Test + void aRedirectOrAnInterruptedRetryOnConfirmationKeepsTheToken() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ServerRedirectException(302, "http://elsewhere")).when(api).confirmPairing(SERVER, "new-tok"); + + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, pairing.pair("123456", "Home").note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + + state.forgetPairing(SERVER); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + ClientPairingService interrupted = new ClientPairingService(state, api, millis -> { + throw new UpstreamResponseException("interrupted"); + }); + + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, interrupted.pair("123456", "Home").note()); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void retriesTheConfirmationAfterAGatewayErrorAndStoresTheToken() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ConfirmationUnavailableException("status 502")).doThrow(new ConfirmationUnavailableException("status 504")).doNothing() + .when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertNull(result.note()); + verify(api, times(3)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void retriesTheConfirmationAfterANetworkErrorWithBackoff() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("reset")).doThrow(new ResourceAccessException("reset")).doNothing() + .when(api).confirmPairing(SERVER, "new-tok"); + + assertNull(pairing.pair("123456", "Home").note()); + + verify(api, times(3)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void givesUpOnTheConfirmationAfterThreeRetriesButKeepsTheTokenAndReturnsTheNote() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + + var result = pairing.pair("123456", "Home"); + + assertTrue(result.paired()); + assertEquals(ClientPairingService.DEFERRED_CONFIRMATION_NOTE, result.note()); + verify(api, times(4)).confirmPairing(SERVER, "new-tok"); + assertEquals(List.of(250L, 500L, 1000L), pauses); + assertEquals("new-tok", state.tokenFor(SERVER).orElseThrow()); + } + + @Test + void aDeferredPairingSurvivesARestartOfTheState() { + when(api.pair(anyString(), anyString(), anyString())).thenReturn(new StoredPairing("new-tok", "new-id", "Home")); + doThrow(new ResourceAccessException("down")).when(api).confirmPairing(SERVER, "new-tok"); + pairing.pair("123456", "Home"); + + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + ClientStateService reloaded = new ClientStateService(configuration, JsonMapper.builder().build()); + + assertEquals("new-tok", reloaded.tokenFor(SERVER).orElseThrow()); + } + + @Test + void concurrentPairingsRunOneAfterTheOther() throws Exception { + AtomicInteger inside = new AtomicInteger(); + AtomicInteger overlaps = new AtomicInteger(); + when(api.pair(anyString(), anyString(), anyString())).thenAnswer(call -> { + if (inside.incrementAndGet() > 1) { + overlaps.incrementAndGet(); + } + Thread.sleep(100); + inside.decrementAndGet(); + return new StoredPairing("tok", "id", "Home"); + }); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future first = pool.submit(() -> pairing.pair("123456", "Home")); + Future second = pool.submit(() -> pairing.pair("123456", "Home")); + int successes = 0; + int conflicts = 0; + for (Future f : List.of(first, second)) { + try { + f.get(10, TimeUnit.SECONDS); + successes++; + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof ConflictException, e.getCause().toString()); + conflicts++; + } + } + assertEquals(1, successes); + assertEquals(1, conflicts); + } finally { + pool.shutdownNow(); + } + + assertEquals(0, overlaps.get()); + verify(api, times(1)).pair(anyString(), anyString(), anyString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java index d0b9362..a7b33f0 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -1,6 +1,7 @@ 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; @@ -8,6 +9,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; import java.time.Duration; import java.util.ArrayList; import java.util.List; @@ -17,20 +19,19 @@ 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; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; class ClientStateServiceTest { - private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final JsonMapper MAPPER = JsonMapper.builder().build(); @TempDir Path tempDir; - private final Configuration configuration = new Configuration(); + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); @BeforeEach void setUp() { @@ -52,6 +53,78 @@ void persistsAndLoadsState() { assertEquals(List.of("state.json"), fileNames()); } + @Test + void aCorruptStateFileIsMovedAsideInsteadOfBeingOverwritten() throws IOException { + Path file = tempDir.resolve("state.json"); + Files.writeString(file, "{\"activeServer\": \"http://a:8080\", \"pairings\": {broken"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + assertNull(state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + state.setActiveServer("http://b:8080"); + + List moved = fileNames().stream().filter(name -> name.startsWith("state.json.corrupt-")).toList(); + assertEquals(1, moved.size()); + assertEquals("{\"activeServer\": \"http://a:8080\", \"pairings\": {broken", Files.readString(tempDir.resolve(moved.getFirst()))); + assertEquals("http://b:8080", new ClientStateService(configuration, MAPPER).getActiveServer()); + } + + @Test + void aStateFileThatHoldsNullIsMovedAsideToo() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "null"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertNull(state.getActiveServer()); + assertTrue(fileNames().stream().anyMatch(name -> name.startsWith("state.json.corrupt-"))); + assertFalse(Files.exists(tempDir.resolve("state.json"))); + } + + @Test + void aFailedSaveLeavesTheStateInMemoryUnchanged() throws IOException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + state.storePairing("http://a:8080", new StoredPairing("tok", "id1", "Laptop")); + Path blocker = tempDir.resolve("blocked"); + Files.writeString(blocker, "not a directory"); + Path file = tempDir.resolve("blocked").resolve("state.json"); + configuration.setStateFile(file.toString()); + ClientStateService failing = new ClientStateService(configuration, MAPPER); + + assertThrows(IllegalStateException.class, () -> failing.setPickupInterval(Duration.ofMinutes(5))); + assertThrows(IllegalStateException.class, () -> failing.setActiveServer("http://b:8080")); + assertThrows(IllegalStateException.class, () -> failing.storePairing("http://b:8080", new StoredPairing("t2", "id2", "x"))); + assertThrows(IllegalStateException.class, () -> failing.updateKnownServers(List.of("http://c:8080"))); + + assertEquals(Duration.ofHours(12), failing.getPickupInterval()); + assertNull(failing.getActiveServer()); + assertFalse(failing.hasPairing("http://b:8080")); + assertEquals(List.of(), failing.getKnownServers()); + } + + @Test + void aFailedSaveKeepsAStoredPairing() throws IOException { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("http://a:8080", new StoredPairing("tok", "id1", "Laptop")); + Files.delete(tempDir.resolve("state.json")); + Files.createDirectory(tempDir.resolve("state.json")); + Files.writeString(tempDir.resolve("state.json").resolve("x"), "x"); + + assertThrows(IllegalStateException.class, () -> state.forgetPairing("http://a:8080")); + + assertTrue(state.hasPairing("http://a:8080")); + } + + @Test + void knowsWhichServersWereAlreadySelected() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + + assertTrue(state.isKnownServer("http://a:8080/")); + assertFalse(state.isKnownServer("http://z:8080")); + } + @Test void setsTheActiveServerOnlyWhileNoneIsSelected() { ClientStateService state = new ClientStateService(configuration, MAPPER); @@ -76,7 +149,31 @@ void keepsTheActiveServerWhenARescanDoesNotFindIt() { state.updateKnownServers(List.of("http://b:8080")); assertEquals("http://a:8080", state.getActiveServer()); - assertEquals(List.of("http://b:8080", "http://a:8080"), state.getKnownServers()); + assertEquals(List.of("http://a:8080", "http://b:8080"), state.getKnownServers()); + } + + @Test + void aScanMergesFoundServersIntoTheKnownOnesWithoutDroppingAny() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "https://garrd.example.com")); + state.setActiveServer("http://a:8080"); + + state.updateKnownServers(List.of("http://c:8080", "http://a:8080")); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://a:8080", "https://garrd.example.com", "http://c:8080"), state.getKnownServers()); + assertEquals(state.getKnownServers(), new ClientStateService(configuration, MAPPER).getKnownServers()); + } + + @Test + void anEmptyScanKeepsTheKnownServers() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + + state.updateKnownServers(List.of()); + + assertEquals(List.of("http://a:8080", "http://b:8080"), state.getKnownServers()); + assertEquals("http://a:8080", state.getActiveServer()); } @Test @@ -93,24 +190,69 @@ void selectsTheFirstDiscoveredServerWhenNoneIsActive() { void rejectsNonPositivePickupIntervals() { ClientStateService state = new ClientStateService(configuration, MAPPER); - assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(Duration.ZERO)); - assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(null)); + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(Duration.ZERO)); + assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(null)); assertEquals(Duration.ofHours(12), state.getPickupInterval()); } @Test - void requiresAnActiveServer() { - assertThrows(ResponseStatusException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); + void rejectsPickupIntervalsAboveOneYear() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + state.setPickupInterval(Duration.ofDays(365)); + InvalidRequestException tooLong = assertThrows(InvalidRequestException.class, () -> state.setPickupInterval(Duration.ofDays(365).plusSeconds(1))); + + assertTrue(tooLong.getMessage().contains("365 days"), tooLong.getMessage()); + assertEquals(Duration.ofDays(365), state.getPickupInterval()); } @Test - void startsWithDefaultsWhenTheStateFileIsUnreadable() throws IOException { - Files.writeString(tempDir.resolve("state.json"), "{not json"); + void anOutOfRangeStoredOrConfiguredIntervalFallsBackToTheDefault() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":999999999,\"knownServers\":[\"http://a:8080\"]}"); - ClientStateService state = new ClientStateService(configuration, MAPPER); + ClientStateService stored = new ClientStateService(configuration, MAPPER); + assertEquals(Duration.ofHours(12), stored.getPickupInterval()); + assertEquals("http://a:8080", stored.getActiveServer()); - assertNull(state.getActiveServer()); - assertEquals(Duration.ofHours(12), state.getPickupInterval()); + configuration.setPickupInterval(Duration.ofDays(4000)); + Files.delete(tempDir.resolve("state.json")); + assertEquals(Duration.ofHours(12), new ClientStateService(configuration, MAPPER).getPickupInterval()); + } + + @Test + void anUnreadableStateFileFailsStartupAndIsLeftInPlace() throws IOException { + Path file = tempDir.resolve("state.json"); + String content = "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://a:8080\"]}"; + Files.writeString(file, content); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("---------")); + org.junit.jupiter.api.Assumptions.assumeFalse(Files.isReadable(file), "the tests run as a user that ignores file permissions"); + try { + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> new ClientStateService(configuration, MAPPER)); + + assertTrue(failure.getMessage().contains(file.toString()), failure.getMessage()); + assertTrue(failure.getMessage().contains("UID"), failure.getMessage()); + assertEquals(List.of("state.json"), fileNames()); + } finally { + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------")); + } + assertEquals(content, Files.readString(file)); + } + + @Test + void aStateFileThatFailsWithAnIoErrorFailsStartupInsteadOfBeingMovedAside() throws IOException { + Path file = tempDir.resolve("state.json"); + Files.createDirectory(file); + + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> new ClientStateService(configuration, MAPPER)); + + assertTrue(failure.getMessage().contains(file.toString()), failure.getMessage()); + assertTrue(Files.isDirectory(file)); + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void requiresAnActiveServer() { + assertThrows(InvalidRequestException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); } private List fileNames() { @@ -221,4 +363,87 @@ void notifiesKnownServersListenersWithoutHoldingTheStateLock() { assertEquals(List.of("http://a:8080"), seenByOtherThread.get()); } + + @Test + void keepsTokensPerNormalizedServerUrlAndReloadsThem() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("HTTPS://Garrd.Example.com:443/", new StoredPairing("tok-1", "id-1", "Home")); + state.storePairing("http://10.0.0.5:38471", new StoredPairing("tok-2", "id-2", "Home")); + + ClientStateService reloaded = new ClientStateService(configuration, MAPPER); + + assertEquals("tok-1", reloaded.tokenFor("https://garrd.example.com").orElseThrow()); + assertEquals("tok-1", reloaded.tokenFor("https://garrd.example.com/").orElseThrow()); + assertEquals("tok-2", reloaded.tokenFor("http://10.0.0.5:38471").orElseThrow()); + assertTrue(reloaded.tokenFor("http://10.0.0.5").isEmpty()); + assertTrue(reloaded.tokenFor("https://garrd.example.com:8443").isEmpty()); + assertEquals("id-1", reloaded.pairingFor("https://garrd.example.com").orElseThrow().id()); + } + + @Test + void forgettingAPairingRemovesItFromDiskAndNotifiesListeners() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + List notified = new ArrayList<>(); + state.addPairingListener(notified::add); + state.storePairing("http://a:8080", new StoredPairing("tok", "id", "Home")); + + assertTrue(state.forgetPairing("http://a:8080")); + assertFalse(state.forgetPairing("http://a:8080")); + + assertEquals(List.of("http://a:8080", "http://a:8080"), notified); + assertFalse(new ClientStateService(configuration, MAPPER).hasPairing("http://a:8080")); + assertFalse(readState().contains("tok")); + } + + @Test + void writesTheStateFileReadableByTheOwnerOnly() throws IOException { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.storePairing("http://a:8080", new StoredPairing("tok", "id", "Home")); + state.setPickupInterval(Duration.ofMinutes(5)); + + Path file = tempDir.resolve("state.json"); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void neverPrintsATokenInTextualForms() { + StoredPairing pairing = new StoredPairing("super-secret-token", "id-1", "Home"); + + assertFalse(pairing.toString().contains("super-secret-token")); + assertFalse(new ClientStateService.ClientState("http://a", 60, null, List.of(), java.util.Map.of("http://a", pairing)).toString().contains("super-secret-token")); + } + + @Test + void migratesStoredServerUrlsToTheirNormalizedForm() throws IOException { + Files.writeString(tempDir.resolve("state.json"), + "{\"activeServer\":\"HTTP://Server:80/\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://server\",\"http://other:8080/\"]," + + "\"pairings\":{\"HTTP://Server:80/\":{\"token\":\"tok\",\"id\":\"i\",\"name\":\"n\"}}}"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertEquals("http://server", state.getActiveServer()); + assertEquals(List.of("http://server", "http://other:8080"), state.getKnownServers()); + assertEquals("tok", state.tokenFor("http://server").orElseThrow()); + } + + @Test + void readsAStateFileWrittenBeforePairingExisted() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{\"activeServer\":\"http://a:8080\",\"pickupIntervalSeconds\":60,\"knownServers\":[\"http://a:8080\"]}"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertEquals("http://a:8080", state.getActiveServer()); + assertFalse(state.hasPairing("http://a:8080")); + } + + private String readState() { + try { + return Files.readString(tempDir.resolve("state.json")); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java index 9847b27..4860911 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/DashboardServiceTest.java @@ -15,20 +15,16 @@ 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; @@ -36,25 +32,25 @@ 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 tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; 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) + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, DateTimeFeature.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"; @@ -67,50 +63,30 @@ class DashboardServiceTest { @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 MutableClock clock = new MutableClock(START); 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 RecordingPublisher publisher; private DashboardService dashboard; @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + MediaGarrdProperties configuration = new MediaGarrdProperties(); configuration.setStateFile(tempDir.resolve("state.json").toString()); configuration.setPickupInterval(Duration.ofHours(12)); state = new ClientStateService(configuration, MAPPER); + state.storePairing(A, new StoredPairing("token-a", "id-a", "Test")); + state.storePairing(B, new StoredPairing("token-b", "id-b", "Test")); 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); + publisher = new RecordingPublisher(); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi, clock), updateCheck, MAPPER, executor, clock); dashboard.start(); } @@ -118,16 +94,11 @@ private void create() { create(Runnable::run); } - @AfterEach - void tearDown() { - broadcasters.forEach(ClientEventBroadcaster::shutdown); - } - - private RecordingEmitter subscribe() { - return (RecordingEmitter) dashboard.subscribe().orElseThrow(); + private RecordingPublisher subscribe() { + return dashboard.subscribe(publisher::subscribe).orElseThrow(); } - private static List drain(RecordingEmitter emitter) throws InterruptedException { + private static List drain(RecordingPublisher emitter) throws InterruptedException { List events = new ArrayList<>(); String next; while ((next = emitter.sent.poll(150, TimeUnit.MILLISECONDS)) != null) { @@ -136,6 +107,12 @@ private static List drain(RecordingEmitter emitter) throws InterruptedEx return events; } + private static List strings(JsonNode array) { + List values = new ArrayList<>(); + array.forEach(node -> values.add(node.asString())); + return values; + } + private static String nameOf(String event) { for (String line : event.split("\n")) { if (line.startsWith("event:")) { @@ -150,7 +127,7 @@ private static List names(List events) { } private void advance(Duration duration) { - now.set(now.get().plus(duration)); + clock.advance(duration); } @Test @@ -174,17 +151,19 @@ void aFirstSubscriberGetsOneFullSnapshotThatReflectsEverythingTheModelHolds() th state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher 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); + JsonNode data = RecordingPublisher.data(snapshot); + assertEquals(A, data.path("activeServer").asString()); + assertEquals(List.of(A), strings(data.path("knownServers"))); + assertEquals("DEGRADED", data.path("link").asString()); + assertTrue(data.path("running").isBoolean() && !data.path("running").asBoolean()); + assertEquals("PT6H", data.path("health").path("backupInterval").asString()); + assertEquals(5, data.path("health").path("backupRetentionCount").asInt()); + assertTrue(data.path("versions").path("server").isObject()); + assertEquals("0.2.0", data.path("versions").path("server").path("latestVersion").asString()); assertTrue(drain(browser).isEmpty()); } @@ -195,12 +174,14 @@ void aLateSubscriberGetsTheLatestSnapshotFollowedByGranularEvents() throws Excep dashboard.streamUp(A); dashboard.runEvent(A, "run-started", "{\"running\":true,\"startedAt\":\"t\"}", true); - RecordingEmitter browser = subscribe(); + RecordingPublisher 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)); + JsonNode snapshot = RecordingPublisher.data(events.get(0)); + assertEquals("LIVE", snapshot.path("link").asString()); + assertTrue(snapshot.path("running").asBoolean()); assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"COMPLETED\"}\n\n", events.get(1)); } @@ -235,7 +216,7 @@ void theLinkIsLiveWhileTheStreamIsUpDegradedWhenOnlyHealthAnswersAndDownOtherwis void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); dashboard.streamUp(A); @@ -244,16 +225,17 @@ void linkChangesArePushedOnlyWhenTheStateChanges() throws Exception { 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\"")); + assertEquals("LIVE", RecordingPublisher.data(links.get(0)).path("state").asString()); + assertEquals(A, RecordingPublisher.data(links.get(0)).path("server").asString()); + assertEquals("CONNECTING", RecordingPublisher.data(links.get(1)).path("state").asString()); + assertEquals("DEGRADED", RecordingPublisher.data(links.get(2)).path("state").asString()); } @Test void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -273,7 +255,7 @@ void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Ex dashboard.tick(); List events = drain(browser); assertEquals(List.of("state"), names(events)); - assertTrue(events.get(0).contains("\"running\":false")); + assertFalse(RecordingPublisher.data(events.get(0)).path("running").asBoolean(true)); assertEquals(false, dashboard.state().running()); advance(Duration.ofSeconds(8)); @@ -285,7 +267,7 @@ void pollsHealthEverySevenToEightSecondsWhileNotLiveAndFeedsTheState() throws Ex void aFailedPollMakesTheLinkDownAndASuccessfulOneRecoversIt() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); @@ -327,7 +309,7 @@ void aLiveLinkIgnoresPollResultsForLinkAndRunningButKeepsTheHealthSummary() thro create(); dashboard.streamUp(A); dashboard.runEvent(A, "state", "{\"running\":false}", false); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doReturn(new ServerStatusDto(true, true, 9, Duration.ofHours(1))).when(serverApi).health(A); @@ -346,7 +328,7 @@ void streamEventsAreForwardedAndKeepRunningInStep() throws Exception { state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); dashboard.runEvent(A, "state", "{\"running\":false,\"at\":\"t\"}", false); @@ -366,7 +348,7 @@ void aConfigChangedEventRefetchesHealthOnceAndPushesTheSummaryOnlyWhenItChanged( state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -390,7 +372,7 @@ void eventsFromAServerThatIsNoLongerActiveAreIgnored() throws Exception { dashboard.streamUp(A); state.setActiveServer(B); dashboard.sync(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -411,7 +393,7 @@ void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws create(); dashboard.streamUp(A); dashboard.runEvent(A, "state", "{\"running\":true}", true); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doThrow(new ResourceAccessException("refused")).when(serverApi).health(B); @@ -421,10 +403,14 @@ void switchingServersPushesASnapshotThatClearsEverythingAboutTheOldOne() throws 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); + JsonNode data = RecordingPublisher.data(snapshot); + assertEquals(B, data.path("activeServer").asString()); + assertEquals(List.of(A, B), strings(data.path("knownServers"))); + assertEquals("CONNECTING", data.path("link").asString()); + assertTrue(data.path("running").isNull()); + assertTrue(data.path("health").isNull()); + assertTrue(data.path("versions").path("server").path("currentVersion").isNull()); + assertEquals("NOT_CHECKED", data.path("versions").path("server").path("checkState").asString()); } @Test @@ -453,7 +439,7 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -464,7 +450,8 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { List events = drain(browser); assertEquals(List.of("snapshot"), names(events)); - assertTrue(events.get(0).contains("\"activeServer\":null") && events.get(0).contains("\"link\":\"DOWN\"")); + assertTrue(RecordingPublisher.data(events.get(0)).path("activeServer").isNull()); + assertEquals("DOWN", RecordingPublisher.data(events.get(0)).path("link").asString()); verify(serverApi, never()).health(anyString()); } @@ -472,7 +459,7 @@ void clearingTheActiveServerGoesDownWithoutPolling() throws Exception { void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysTheSame() throws Exception { state.setActiveServer(A); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); state.updateKnownServers(List.of(A, B)); @@ -486,7 +473,7 @@ void knownServerChangesArePushedOnceAndWithoutASnapshotWhenTheActiveServerStaysT void aDiscoveryThatPicksTheFirstActiveServerPushesOneSnapshot() throws Exception { when(serverApi.health(anyString())).thenThrow(new ResourceAccessException("refused")); create(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); state.updateKnownServers(List.of(A, B)); @@ -502,7 +489,7 @@ void theServerVersionIsFetchedOnLinkUpAndAServerSwitchNotOnEveryRead() throws Ex verify(serverApi, times(1)).serverVersion(A); dashboard.state(); - dashboard.subscribe(); + dashboard.subscribe(publisher::subscribe); dashboard.state(); verify(serverApi, times(1)).serverVersion(A); @@ -528,7 +515,7 @@ void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exce state.setActiveServer(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -543,7 +530,7 @@ void theServerVersionIsRefetchedAtMostHourlyAndPushedWhenItChanges() throws Exce 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)); + assertEquals("0.2.0", RecordingPublisher.data(events.get(0)).path("server").path("currentVersion").asString()); } @Test @@ -553,7 +540,7 @@ void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { create(); ArgumentCaptor> listener = ArgumentCaptor.forClass(Consumer.class); verify(updateCheck).addStatusListener(listener.capture()); - RecordingEmitter browser = subscribe(); + RecordingPublisher 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); @@ -562,8 +549,10 @@ void theClientsOwnUpdateCheckIsPushedAsAVersionsEvent() throws Exception { 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\":{")); + JsonNode versions = RecordingPublisher.data(events.get(0)); + assertEquals("0.3.0", versions.path("client").path("latestVersion").asString()); + assertTrue(versions.path("client").path("updateAvailable").asBoolean()); + assertTrue(versions.path("server").isObject()); } @Test @@ -604,7 +593,7 @@ void aServerIsConnectingUntilItsFirstAnswerAndOnlyThenDownWithAnUnavailableVersi state.setActiveServer(A); doThrow(new ResourceAccessException("refused")).when(serverApi).health(A); create(queued::add); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); DashboardState before = dashboard.state(); @@ -639,7 +628,7 @@ void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws doReturn(notChecked).doReturn(notChecked).doReturn(SERVER_VERSION).when(serverApi).serverVersion(A); create(); dashboard.streamUp(A); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); clearInvocations(serverApi); @@ -654,7 +643,7 @@ void aServerVersionThatWasNotCheckedYetIsFetchedAgainWithinHalfAMinute() throws 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)); + assertEquals("OK", RecordingPublisher.data(events.get(0)).path("server").path("checkState").asString()); } @Test @@ -677,7 +666,7 @@ void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChan 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(); + RecordingPublisher browser = subscribe(); browser.next(); advance(Duration.ofSeconds(8)); @@ -695,7 +684,7 @@ void whileDegradedTheClientChecksTheArchiveListOncePerMinuteAndPushesBackupsChan 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)); + assertEquals("2026-11-12T10:01:09Z", RecordingPublisher.data(events.get(0)).path("at").asString()); advance(Duration.ofSeconds(61)); dashboard.tick(); @@ -725,7 +714,7 @@ void aRunThatFinishesWhileDegradedRebaselinesTheArchiveListInsteadOfAnnouncingIt create(); advance(Duration.ofSeconds(8)); dashboard.tick(); - RecordingEmitter browser = subscribe(); + RecordingPublisher browser = subscribe(); browser.next(); doReturn(IDLE).when(serverApi).health(A); @@ -780,4 +769,79 @@ void aFailingArchiveListingIsRetriedOnlyOncePerMinute() { dashboard.tick(); verify(serverApi, times(2)).listBackups(A); } + + @Test + void aServerWithoutAStoredTokenRequiresPairingAndShowsNoDetails() { + state.forgetPairing(A); + create(); + state.setActiveServer(A); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REQUIRED, dashboard.state().pairing()); + assertEquals(null, dashboard.state().health()); + } + + @Test + void aRejectedTokenOnTheHealthCheckMarksPairingRejectedAndKeepsTheServerReachable() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + + DashboardState result = dashboard.state(); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, result.pairing()); + assertEquals(wellatleastitried.mediagarrdclient.dto.LinkState.DEGRADED, result.link()); + } + + @Test + void aDeferredPairingWhoseHealthCheckLaterGetsA401BecomesRejected() { + create(); + state.forgetPairing(A); + state.setActiveServer(A); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.storePairing(A, new StoredPairing("deferred-token", "id-d", "Test")); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } + + @Test + void pairingAgainClearsTheRejection() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + doReturn(IDLE).when(serverApi).health(A); + + state.storePairing(A, new StoredPairing("new-token", "id-new", "Test")); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + } + + @Test + void aHealthCheckThatClearsTheRejectionTellsListenersSoTheStreamCanRestart() { + create(); + doThrow(new PairingRequiredException("rejected")).when(serverApi).health(A); + state.setActiveServer(A); + List recovered = new ArrayList<>(); + dashboard.addRecoveryListener(recovered::add); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + + doReturn(IDLE).when(serverApi).health(A); + advance(Duration.ofSeconds(8)); + dashboard.tick(); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + assertEquals(List.of(A), recovered); + } + + @Test + void aTokenRejectionSeenByAnyServerCallMarksThePairingRejectedAtOnce() { + create(); + state.setActiveServer(A); + org.mockito.ArgumentCaptor> listener = org.mockito.ArgumentCaptor.forClass(java.util.function.Consumer.class); + verify(serverApi).addTokenRejectedListener(listener.capture()); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.PAIRED, dashboard.state().pairing()); + + listener.getValue().accept(A); + + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java new file mode 100644 index 0000000..1c718e6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/LoginAttemptsTest.java @@ -0,0 +1,191 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class LoginAttemptsTest { + + private final MutableClock clock = new MutableClock(Instant.parse("2026-11-19T12:00:00Z")); + private final LoginAttempts attempts = new LoginAttempts(clock, 3); + + @Test + void allowsAFewFailuresThenLocksWithAGrowingDelay() { + for (int i = 0; i < LoginAttempts.FREE_FAILURES; i++) { + attempts.failed("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + attempts.failed("10.0.0.1"); + assertEquals(Duration.ofSeconds(5), attempts.lockedFor("10.0.0.1").orElseThrow()); + + clock.advance(Duration.ofSeconds(5)); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + attempts.failed("10.0.0.1"); + assertEquals(Duration.ofSeconds(10), attempts.lockedFor("10.0.0.1").orElseThrow()); + } + + @Test + void capsTheDelay() { + for (int i = 0; i < 40; i++) { + attempts.failed("10.0.0.1"); + clock.advance(LoginAttempts.MAX_LOCK); + } + + attempts.failed("10.0.0.1"); + + assertEquals(LoginAttempts.MAX_LOCK, attempts.lockedFor("10.0.0.1").orElseThrow()); + } + + @Test + void trackSourcesSeparatelyAndForgetAfterASuccess() { + for (int i = 0; i < 5; i++) { + attempts.failed("10.0.0.1"); + } + + assertTrue(attempts.lockedFor("10.0.0.1").isPresent()); + assertTrue(attempts.lockedFor("10.0.0.2").isEmpty()); + attempts.succeeded("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + @Test + void forgetsOldFailures() { + for (int i = 0; i < 5; i++) { + attempts.failed("10.0.0.1"); + } + + clock.advance(LoginAttempts.FORGET_AFTER); + + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + attempts.failed("10.0.0.1"); + assertTrue(attempts.lockedFor("10.0.0.1").isEmpty()); + } + + @Test + void keepsAtMostTheConfiguredNumberOfSources() { + for (int i = 0; i < 4; i++) { + for (int n = 0; n < 5; n++) { + attempts.failed("10.0.0." + i); + } + } + + assertTrue(attempts.lockedFor("10.0.0.0").isEmpty()); + assertTrue(attempts.lockedFor("10.0.0.3").isPresent()); + } + + @Test + void refusesASecondAttemptFromASourceWhileOneIsInFlight() { + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.0.0.1").isPresent()); + assertTrue(attempts.tryBegin("10.0.0.2").isEmpty()); + + attempts.failed("10.0.0.1"); + + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + attempts.abandon("10.0.0.1"); + assertTrue(attempts.tryBegin("10.0.0.1").isEmpty()); + } + + @Test + void lockoutFromFailuresIsHonouredByTryBegin() { + for (int i = 0; i < LoginAttempts.FREE_FAILURES + 1; i++) { + attempts.tryBegin("10.0.0.1"); + attempts.failed("10.0.0.1"); + } + + assertEquals(Duration.ofSeconds(5), attempts.tryBegin("10.0.0.1").orElseThrow()); + } + + private void drainBucket() { + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY; i++) { + assertTrue(attempts.tryBegin("10.9.0." + i).isEmpty()); + } + } + + @Test + void anEmptyBucketRefusesEverySourceWithTheTimeToTheNextTokenInsteadOfLockingAnyone() { + drainBucket(); + + assertEquals(Duration.ofSeconds(2), attempts.tryBegin("10.8.0.1").orElseThrow()); + clock.advance(Duration.ofSeconds(1)); + assertEquals(Duration.ofSeconds(1), attempts.tryBegin("10.8.0.1").orElseThrow()); + clock.advance(Duration.ofSeconds(1)); + assertTrue(attempts.tryBegin("10.8.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.8.0.2").isPresent()); + } + + @Test + void aRefusedAttemptDoesNotLeaveASourceReserved() { + drainBucket(); + + assertTrue(attempts.tryBegin("10.8.0.1").isPresent()); + clock.advance(Duration.ofSeconds(2)); + + assertTrue(attempts.tryBegin("10.8.0.1").isEmpty()); + } + + @Test + void aSuccessfulLoginGivesItsTokenBackButNeverBeyondTheCapacity() { + assertTrue(attempts.tryBegin("10.7.0.1").isEmpty()); + attempts.succeeded("10.7.0.1"); + attempts.succeeded("10.7.0.1"); + attempts.succeeded("10.7.0.2"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY; i++) { + assertTrue(attempts.tryBegin("10.6.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.6.1.1").isPresent()); + } + + @Test + void anAbandonedAttemptGivesItsTokenBack() { + drainBucket(); + clock.advance(Duration.ofSeconds(2)); + assertTrue(attempts.tryBegin("10.5.0.1").isEmpty()); + assertTrue(attempts.tryBegin("10.5.0.2").isPresent()); + + attempts.abandon("10.5.0.1"); + + assertTrue(attempts.tryBegin("10.5.0.2").isEmpty()); + } + + @Test + void aFailureKeepsItsTokenSpent() { + assertTrue(attempts.tryBegin("10.4.0.1").isEmpty()); + attempts.failed("10.4.0.1"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY - 1; i++) { + assertTrue(attempts.tryBegin("10.3.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.3.1.1").isPresent()); + } + + @Test + void aRefusalWhileBusyDoesNotSpendAToken() { + assertTrue(attempts.tryBegin("10.2.0.1").isEmpty()); + for (int i = 0; i < 100; i++) { + assertEquals(LoginAttempts.BUSY_RETRY, attempts.tryBegin("10.2.0.1").orElseThrow()); + } + attempts.failed("10.2.0.1"); + for (int i = 0; i < LoginAttempts.BUCKET_CAPACITY - 1; i++) { + assertTrue(attempts.tryBegin("10.1.0." + i).isEmpty(), "attempt " + i); + } + + assertTrue(attempts.tryBegin("10.1.1.1").isPresent()); + } + + @Test + void aSucceededCallWithoutAReservationDoesNotRefund() { + drainBucket(); + + attempts.succeeded("10.0.9.9"); + attempts.abandon("10.0.9.9"); + + assertTrue(attempts.tryBegin("10.8.0.1").isPresent()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java b/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java new file mode 100644 index 0000000..83ac6e4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/MutableClock.java @@ -0,0 +1,43 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +final class MutableClock extends Clock { + + private volatile Instant now; + + MutableClock() { + this(Instant.parse("2026-10-26T00:00:00Z")); + } + + MutableClock(Instant start) { + this.now = start; + } + + void set(Instant instant) { + now = instant; + } + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java new file mode 100644 index 0000000..bcb0e5e --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/PasswordServiceTest.java @@ -0,0 +1,152 @@ +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.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +class PasswordServiceTest { + + private static final JsonMapper MAPPER = JsonMapper.builder().build(); + private static final int FAST = 1000; + + @TempDir + Path tempDir; + + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); + + @BeforeEach + void setUp() { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + } + + private PasswordService service() { + return new PasswordService(configuration, MAPPER, FAST); + } + + @Test + void startsWithoutAPasswordAndLetsTheFirstCallerSetOne() { + PasswordService passwords = service(); + assertFalse(passwords.isConfigured()); + assertFalse(passwords.matches("anything")); + + passwords.setInitial("correct horse"); + + assertTrue(passwords.isConfigured()); + assertTrue(passwords.matches("correct horse")); + assertFalse(passwords.matches("correct horsf")); + assertFalse(passwords.matches(null)); + assertTrue(service().matches("correct horse")); + } + + @Test + void refusesASecondInitialPassword() { + PasswordService passwords = service(); + passwords.setInitial("correct horse"); + + assertThrows(ConflictException.class, () -> passwords.setInitial("another one")); + + assertTrue(passwords.matches("correct horse")); + } + + @Test + void rejectsPasswordsThatAreTooShortOrTooLong() { + PasswordService passwords = service(); + + assertThrows(InvalidRequestException.class, () -> passwords.setInitial("short")); + assertThrows(InvalidRequestException.class, () -> passwords.setInitial(null)); + assertThrows(InvalidRequestException.class, () -> passwords.setInitial("x".repeat(PasswordService.MAX_LENGTH + 1))); + assertFalse(passwords.isConfigured()); + assertFalse(Files.exists(tempDir.resolve("password.json"))); + } + + @Test + void theStoredFileHoldsOnlyAHashWithItsParameters() throws IOException { + PasswordService first = service(); + first.setInitial("correct horse"); + Path file = tempDir.resolve("password.json"); + String content = Files.readString(file); + JsonNode json = MAPPER.readTree(content); + + assertFalse(content.contains("correct horse")); + assertEquals(FAST, json.get("iterations").asInt()); + assertEquals(16, java.util.Base64.getDecoder().decode(json.get("salt").asString()).length); + assertEquals(32, java.util.Base64.getDecoder().decode(json.get("hash").asString()).length); + if (Files.getFileStore(file).supportsFileAttributeView("posix")) { + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + } + + @Test + void twoInstallsWithTheSamePasswordGetDifferentSalts() throws IOException { + service().setInitial("correct horse"); + String first = Files.readString(tempDir.resolve("password.json")); + Files.delete(tempDir.resolve("password.json")); + service().setInitial("correct horse"); + + assertFalse(first.equals(Files.readString(tempDir.resolve("password.json")))); + } + + @Test + void anEnvironmentPasswordOverridesAndDisablesSetting() { + configuration.setPassword("from the environment"); + PasswordService passwords = service(); + + assertTrue(passwords.isConfigured()); + assertTrue(passwords.isFromEnvironment()); + assertTrue(passwords.matches("from the environment")); + assertFalse(passwords.matches("something else")); + assertThrows(ConflictException.class, () -> passwords.setInitial("a new password")); + } + + @Test + void anEnvironmentPasswordWinsOverAStoredOne() { + service().setInitial("stored password"); + configuration.setPassword("from the environment"); + PasswordService passwords = service(); + + assertTrue(passwords.matches("from the environment")); + assertFalse(passwords.matches("stored password")); + } + + @Test + void resetRemovesTheStoredPasswordSoAnotherCanBeSet() { + service().setInitial("old password"); + configuration.setResetPassword(true); + + PasswordService passwords = service(); + + assertFalse(passwords.isConfigured()); + assertFalse(Files.exists(tempDir.resolve("password.json"))); + passwords.setInitial("new password"); + assertTrue(passwords.matches("new password")); + } + + @Test + void refusesToStartOnACorruptPasswordFileInsteadOfOpeningTheFirstVisitWindow() throws IOException { + Files.writeString(tempDir.resolve("password.json"), "{not json"); + + IllegalStateException e = assertThrows(IllegalStateException.class, this::service); + + assertTrue(e.getMessage().contains("CLIENT_RESET_PASSWORD")); + } + + @Test + void usesTheDocumentedIterationCountByDefault() { + assertEquals(600_000, PasswordService.ITERATIONS); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java new file mode 100644 index 0000000..1b6ec02 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/PickupScheduleTest.java @@ -0,0 +1,68 @@ +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.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class PickupScheduleTest { + + private static final Duration INTERVAL = Duration.ofHours(12); + + private final MutableClock clock = new MutableClock(); + private final PickupSchedule schedule = new PickupSchedule(clock); + + @Test + void aClientThatNeverPickedUpIsDueNow() { + assertTrue(schedule.due(null, INTERVAL)); + } + + @Test + void aPickupIsDueOneIntervalAfterTheLastOne() { + Instant last = clock.instant().minus(Duration.ofHours(5)); + + assertFalse(schedule.due(last, INTERVAL)); + assertEquals(last.plus(INTERVAL), schedule.dueAt(last, INTERVAL)); + clock.advance(Duration.ofHours(7)); + assertTrue(schedule.due(last, INTERVAL)); + } + + @Test + void aLastPickupInTheFutureDoesNotStallTheSchedule() { + assertTrue(schedule.due(clock.instant().plus(Duration.ofDays(30)), INTERVAL)); + } + + @Test + void failuresBackOffAndCapThenResetOnSuccess() { + Duration[] expected = {Duration.ofMinutes(1), Duration.ofMinutes(2), Duration.ofMinutes(5), Duration.ofMinutes(10), Duration.ofMinutes(15), Duration.ofMinutes(15)}; + for (Duration wait : expected) { + Instant retry = schedule.failed(); + assertEquals(clock.instant().plus(wait), retry); + assertFalse(schedule.due(null, INTERVAL)); + clock.advance(wait); + assertTrue(schedule.due(null, INTERVAL)); + } + + schedule.reset(); + assertTrue(schedule.due(null, INTERVAL)); + assertEquals(clock.instant().plus(Duration.ofMinutes(1)), schedule.failed()); + } + + @Test + void aClockThatJumpsBackwardDoesNotStallTheRetry() { + schedule.failed(); + schedule.failed(); + schedule.failed(); + schedule.failed(); + schedule.failed(); + clock.advance(Duration.ofHours(-5)); + + assertFalse(schedule.due(null, INTERVAL)); + clock.advance(Duration.ofMinutes(15)); + assertTrue(schedule.due(null, INTERVAL)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java new file mode 100644 index 0000000..52b2a29 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ReconnectPolicyTest.java @@ -0,0 +1,58 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +import wellatleastitried.mediagarrdclient.service.ReconnectPolicy.Outcome; + +class ReconnectPolicyTest { + + private static final long LONG = Duration.ofSeconds(60).toNanos(); + private static final long SHORT = Duration.ofSeconds(1).toNanos(); + + private final ReconnectPolicy policy = new ReconnectPolicy(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofMinutes(5), Duration.ofSeconds(5)); + + @Test + void failuresBackOffExponentiallyUpToTheMaximum() { + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(2), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(4), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(8), policy.next(Outcome.FAILED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(8), policy.next(Outcome.FAILED, false, SHORT).delay()); + } + + @Test + void aLongStreamThatDeliveredEventsResetsTheBackoff() { + policy.next(Outcome.FAILED, false, SHORT); + policy.next(Outcome.FAILED, false, SHORT); + + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, true, LONG).delay()); + } + + @Test + void aShortStreamThatDeliveredEventsDoesNotResetTheBackoff() { + policy.next(Outcome.FAILED, false, SHORT); + + assertEquals(Duration.ofSeconds(2), policy.next(Outcome.FAILED, true, SHORT).delay()); + } + + @Test + void aRolloverReconnectsAtOnceUnlessItWasShortLived() { + assertEquals(Outcome.ROLLOVER, policy.next(Outcome.ROLLOVER, true, LONG).outcome()); + assertEquals(Outcome.FAILED, policy.next(Outcome.ROLLOVER, true, SHORT).outcome()); + } + + @Test + void anUnsupportedServerIsRetriedAfterTheLongDelayWithoutGrowingTheBackoff() { + assertEquals(Duration.ofMinutes(5), policy.next(Outcome.UNSUPPORTED, false, SHORT).delay()); + assertEquals(Duration.ofSeconds(1), policy.next(Outcome.FAILED, false, SHORT).delay()); + } + + @Test + void aRejectionIsPassedThrough() { + assertEquals(Outcome.REJECTED, policy.next(Outcome.REJECTED, false, SHORT).outcome()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java b/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java new file mode 100644 index 0000000..9959501 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/RecordingPublisher.java @@ -0,0 +1,68 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class RecordingPublisher implements ClientEventPublisher { + + final BlockingQueue sent = new LinkedBlockingQueue<>(); + private volatile boolean subscribed; + + @Override + public void publish(String name, String data) { + if (subscribed) { + sent.add(frame(name, data)); + } + } + + Optional subscribe(List initial) { + subscribed = true; + initial.forEach(event -> sent.add(frame(event.name(), event.data()))); + return Optional.of(this); + } + + 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 String eventName(String frame) { + for (String line : frame.split("\n")) { + if (line.startsWith("event:")) { + return line.substring("event:".length()); + } + } + return ""; + } + + static JsonNode data(String frame) { + for (String line : frame.split("\n")) { + if (line.startsWith("data:")) { + return JsonMapper.builder().build().readTree(line.substring("data:".length())); + } + } + throw new AssertionError("no data line in " + frame); + } + + private static String frame(String name, String data) { + return "event:" + name + "\ndata:" + data + "\n\n"; + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java new file mode 100644 index 0000000..dc5bc8c --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ScheduledPickupTest.java @@ -0,0 +1,599 @@ +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.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +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.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +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.junit.jupiter.api.io.TempDir; +import org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; + +class ScheduledPickupTest { + + private static final String SERVER = "http://server:8080"; + private static final Duration INTERVAL = Duration.ofHours(12); + private static final BackupDto LATEST = new BackupDto("b2", "b2-media-backup.zip", 4, Instant.EPOCH); + private static final BackupDto OLDER = new BackupDto("b1", "b1-media-backup.zip", 4, Instant.EPOCH); + + @TempDir + Path tempDir; + + private final ServerApiService api = mock(ServerApiService.class); + private final MutableClock clock = new MutableClock(); + private final List services = new ArrayList<>(); + private MediaGarrdProperties configuration; + private ClientStateService state; + private Path downloads; + + @BeforeEach + void setUp() throws IOException { + downloads = tempDir.resolve("downloads"); + Files.createDirectories(downloads); + configuration = new MediaGarrdProperties(); + configuration.setDownloadDirectory(downloads.toString()); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(INTERVAL); + state = new ClientStateService(configuration, new JsonMapper()); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); + when(api.downloadById(eq(SERVER), anyString(), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + } + + @AfterEach + void tearDown() { + services.forEach(BackupPickupService::shutdown); + } + + @Test + void aRestartedClientThatIsOverdueDownloadsOnTheFirstTick() throws Exception { + pairedState().recordPickup(SERVER, clock.instant().minus(INTERVAL).minusSeconds(1)); + + BackupPickupService restarted = restart(); + tick(restarted); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aRestartedClientThatIsNotDueWaitsForTheOriginalDueTime() throws Exception { + Instant last = clock.instant().minus(Duration.ofHours(5)); + pairedState().recordPickup(SERVER, last); + + BackupPickupService restarted = restart(); + tick(restarted); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofHours(7).minusSeconds(1)); + tick(restarted); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofSeconds(1)); + tick(restarted); + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aClientThatNeverPickedUpDownloadsAtOnce() throws Exception { + pairedState(); + + tick(start()); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void anAlreadyDownloadedLatestArchiveCountsAsAPickup() throws Exception { + pairedState(); + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[4]); + + tick(start()); + + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void anUnpairedClientStaysQuietAndPicksUpOnceItIsPaired() throws Exception { + state.setActiveServer(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + clock.advance(Duration.ofHours(1)); + tick(pickup); + + verify(api, never()).listBackups(anyString()); + assertNull(state.getLastPickupAt()); + + state.storePairing(SERVER, new StoredPairing("token", "id", "name")); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + @Test + void aServerThatIsDownIsRetriedOnABackoffUntilItAnswers() throws Exception { + pairedState(); + doThrow(new ResourceAccessException("connection refused")).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + tick(pickup); + verify(api, times(1)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + + doReturn(List.of(LATEST, OLDER)).when(api).listBackups(SERVER); + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void aServerWithoutBackupsIsReportedOnceAtInfoAndNeverAsAWarning() throws Exception { + pairedState(); + doReturn(List.of()).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(BackupPickupService.class); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + logger.addAppender(logs); + try { + for (int i = 0; i < 4; i++) { + tick(pickup); + clock.advance(Duration.ofMinutes(20)); + } + verify(api, times(4)).listBackups(SERVER); + } finally { + logger.detachAppender(logs); + } + + assertTrue(logs.list.stream().noneMatch(event -> event.getLevel().isGreaterOrEqual(ch.qos.logback.classic.Level.WARN))); + assertEquals(1, logs.list.stream().filter(event -> event.getLevel() == ch.qos.logback.classic.Level.INFO && event.getFormattedMessage().contains("no backups")).count()); + } + + @Test + void switchingTheActiveServerReportsAnEmptyServerAgain() throws Exception { + pairedState(); + doReturn(List.of()).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(BackupPickupService.class); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + logger.addAppender(logs); + try { + tick(pickup); + clock.advance(Duration.ofMinutes(20)); + state.setActiveServer("http://other:8080"); + state.setActiveServer(SERVER); + tick(pickup); + } finally { + logger.detachAppender(logs); + } + + assertEquals(2, logs.list.stream().filter(event -> event.getLevel() == ch.qos.logback.classic.Level.INFO && event.getFormattedMessage().contains("no backups")).count()); + } + + @Test + void aRejectedTokenIsRetriedOnABackoffAndKeepsTheLastPickup() throws Exception { + Instant last = clock.instant().minus(INTERVAL).minusSeconds(1); + pairedState().recordPickup(SERVER, last); + doThrow(new PairingRequiredException("rejected")).when(api).listBackups(SERVER); + BackupPickupService pickup = start(); + + tick(pickup); + tick(pickup); + + verify(api, times(1)).listBackups(SERVER); + assertEquals(last, pairedState().getLastPickupAt()); + } + + @Test + void aDownloadInterruptedByARestartIsRepeatedAfterwards() throws Exception { + pairedState(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("connection reset")); + + tick(restart()); + + assertNull(pairedState().getLastPickupAt()); + + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + tick(restart()); + + verify(api, times(2)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), pairedState().getLastPickupAt()); + } + + @Test + void shorteningTheIntervalMakesAnOverduePickupDue() throws Exception { + pairedState().recordPickup(SERVER, clock.instant().minus(Duration.ofHours(5))); + BackupPickupService pickup = start(); + tick(pickup); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + pickup.updatePickupInterval(Duration.ofHours(4)); + tick(pickup); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void lengtheningTheIntervalMovesTheDueTimeFromTheLastPickup() throws Exception { + Instant last = clock.instant().minus(Duration.ofHours(5)); + pairedState().recordPickup(SERVER, last); + BackupPickupService pickup = start(); + + pickup.updatePickupInterval(Duration.ofHours(8)); + assertEquals(last.plus(Duration.ofHours(8)), pickup.nextPickup()); + clock.advance(Duration.ofHours(3).minusSeconds(1)); + tick(pickup); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + + clock.advance(Duration.ofSeconds(1)); + tick(pickup); + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + } + + @Test + void aManualDownloadOfTheLatestArchiveRecordsAPickup() throws Exception { + pairedState(); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupLatestTask().taskId()); + + assertEquals("COMPLETED", progress.status()); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + @Test + void aManualDownloadOfAnOlderArchiveDoesNotRecordAPickup() throws Exception { + pairedState(); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()); + + assertEquals("COMPLETED", progress.status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aFailedManualDownloadDoesNotRecordAPickup() throws Exception { + pairedState(); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new DownloadFailedException("disk full")); + BackupPickupService pickup = start(); + + PickupProgressDto progress = awaitFinished(pickup, pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aScheduledPickupAndAManualOneNeverDownloadTheSameBackupTwice() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + String taskId = pickup.startPickupLatestTask().taskId(); + release.countDown(); + awaitIdle(pickup); + awaitFinished(pickup, taskId); + + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void switchingTheActiveServerMakesTheNextPickupDueAtOnce() throws Exception { + pairedState().recordPickup(SERVER, clock.instant()); + + state.setActiveServer(SERVER); + assertEquals(clock.instant(), state.getLastPickupAt()); + + state.setActiveServer("http://other:8080"); + + assertNull(state.getLastPickupAt()); + assertNull(new ClientStateService(configuration, new JsonMapper()).getLastPickupAt()); + } + + @Test + void aFailedRecordOfThePickupBacksOffInsteadOfRetryingEveryTick() throws Exception { + ClientStateService failing = mock(ClientStateService.class); + when(failing.getActiveServer()).thenReturn(SERVER); + when(failing.requireActiveServer()).thenReturn(SERVER); + when(failing.hasPairing(SERVER)).thenReturn(true); + when(failing.getPickupInterval()).thenReturn(INTERVAL); + doThrow(new IllegalStateException("disk full")).when(failing).recordPickup(any(), any()); + BackupPickupService pickup = new BackupPickupService(configuration, failing, api, clock); + services.add(pickup); + + tick(pickup); + tick(pickup); + verify(api, times(1)).listBackups(SERVER); + + clock.advance(Duration.ofMinutes(1)); + tick(pickup); + verify(api, times(2)).listBackups(SERVER); + } + + @Test + void aPickupThatFinishesAfterTheServerWasSwitchedDoesNotDelayTheNewServer() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + state.setActiveServer("http://other:8080"); + release.countDown(); + awaitIdle(pickup); + + assertNull(state.getLastPickupAt()); + assertNull(new ClientStateService(configuration, new JsonMapper()).getLastPickupAt()); + } + + @Test + void aManualLatestDownloadThatFinishesAfterTheServerWasSwitchedDoesNotDelayTheNewServer() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + String taskId = pickup.startPickupLatestTask().taskId(); + started.await(5, TimeUnit.SECONDS); + state.setActiveServer("http://other:8080"); + release.countDown(); + + assertEquals("COMPLETED", awaitFinished(pickup, taskId).status()); + assertNull(state.getLastPickupAt()); + } + + @Test + void aScheduledPickupIsRecordedBeforeItsTaskReportsCompleted() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + ClientStateService spied = spy(state); + BackupPickupService pickup = new BackupPickupService(configuration, spied, api, clock); + services.add(pickup); + List statusWhenRecorded = new ArrayList<>(); + String[] taskId = new String[1]; + doAnswer(invocation -> { + statusWhenRecorded.add(pickup.pickupProgress(taskId[0]).status()); + return invocation.callRealMethod(); + }).when(spied).recordPickup(anyString(), any()); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + taskId[0] = pickup.startPickupLatestTask().taskId(); + release.countDown(); + awaitIdle(pickup); + + assertEquals(List.of("RUNNING"), statusWhenRecorded); + assertEquals("COMPLETED", pickup.pickupProgress(taskId[0]).status()); + } + + @Test + void aTickDuringAManualLatestDownloadDefersAndTheManualDownloadRecordsThePickup() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + BackupPickupService pickup = start(); + + String taskId = pickup.startPickupLatestTask().taskId(); + started.await(5, TimeUnit.SECONDS); + tick(pickup); + + assertNull(state.getLastPickupAt()); + clock.advance(Duration.ofSeconds(30)); + tick(pickup); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + + release.countDown(); + assertEquals("COMPLETED", awaitFinished(pickup, taskId).status()); + + assertEquals(clock.instant(), state.getLastPickupAt()); + clock.advance(Duration.ofMinutes(5)); + tick(pickup); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void aPartFileLeftByACrashIsRemovedByTheNextPickup() throws Exception { + pairedState(); + Path junk = downloads.resolve("b0-media-backup-AD.zip.part"); + Path unrelated = downloads.resolve("notes.txt"); + Files.write(junk, new byte[7]); + Files.write(unrelated, new byte[1]); + + tick(start()); + + verify(api, times(1)).downloadById(eq(SERVER), eq("b2"), any(), any()); + assertEquals(clock.instant(), state.getLastPickupAt()); + assertFalse(Files.exists(junk)); + assertTrue(Files.exists(unrelated)); + assertTrue(Files.exists(downloads.resolve("b2-media-backup-AD.zip"))); + } + + @Test + void aPartFileIsRemovedBeforeAManualPickupToo() throws Exception { + pairedState(); + Path junk = downloads.resolve("b9-media-backup.zip.part"); + Files.write(junk, new byte[7]); + BackupPickupService pickup = start(); + + assertEquals("COMPLETED", awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()).status()); + + assertFalse(Files.exists(junk)); + } + + @Test + void aPartFileLeftByACrashIsRemovedAtStartup() throws Exception { + Path junk = downloads.resolve("b2-media-backup-AD.zip.part"); + Files.write(junk, new byte[7]); + + start().removeStalePartFilesAtStartup(); + + assertFalse(Files.exists(junk)); + } + + @Test + void aPartFileOfATransferInProgressIsNeverRemoved() throws Exception { + pairedState(); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target.resolveSibling(target.getFileName() + ".part"), new byte[2]); + started.countDown(); + release.await(5, TimeUnit.SECONDS); + Files.write(target, new byte[4]); + return target; + }); + Path junk = downloads.resolve("b0-media-backup.zip.part"); + Files.write(junk, new byte[7]); + BackupPickupService pickup = start(); + + pickup.scheduledPickup(); + started.await(5, TimeUnit.SECONDS); + assertEquals("COMPLETED", awaitFinished(pickup, pickup.startPickupByIdTask("b1").taskId()).status()); + Path inProgress = downloads.resolve("b2-media-backup-AD.zip.part"); + boolean keptWhileRunning = Files.exists(inProgress); + boolean junkGone = !Files.exists(junk); + release.countDown(); + awaitIdle(pickup); + + assertTrue(keptWhileRunning); + assertTrue(junkGone); + assertEquals(clock.instant(), state.getLastPickupAt()); + } + + private ClientStateService pairedState() { + state.setActiveServer(SERVER); + state.storePairing(SERVER, new StoredPairing("token", "id", "name")); + return state; + } + + private BackupPickupService restart() { + state = new ClientStateService(configuration, new JsonMapper()); + return start(); + } + + private BackupPickupService start() { + BackupPickupService service = new BackupPickupService(configuration, state, api, clock); + services.add(service); + return service; + } + + private void tick(BackupPickupService pickup) throws InterruptedException { + pickup.scheduledPickup(); + awaitIdle(pickup); + } + + private static void awaitIdle(BackupPickupService pickup) throws InterruptedException { + for (int attempt = 0; attempt < 500 && pickup.scheduledRunning(); attempt++) { + Thread.sleep(10); + } + if (pickup.scheduledRunning()) { + throw new AssertionError("The scheduled pickup did not finish"); + } + } + + private static PickupProgressDto awaitFinished(BackupPickupService pickup, String taskId) throws InterruptedException { + for (int attempt = 0; attempt < 500; attempt++) { + PickupProgressDto progress = pickup.pickupProgress(taskId); + if (progress.status().equals("COMPLETED") || progress.status().equals("FAILED")) { + return progress; + } + Thread.sleep(10); + } + throw new AssertionError("Pickup task " + taskId + " did not finish"); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java index b28b7c1..92f90db 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SemVerTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; class SemVerTest { @@ -30,16 +31,12 @@ void parsesPrereleaseAndIgnoresBuildMetadata() { } @ParameterizedTest + @NullSource @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); diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java index 9b41876..cd76332 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -2,8 +2,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; import java.io.IOException; import java.io.OutputStream; @@ -15,6 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -29,11 +32,15 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.api.ApiExceptionHandler; import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.WebhookStatusDto; +import wellatleastitried.mediagarrdclient.dto.WebhookTestDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; class ServerApiServiceTest { @@ -42,12 +49,15 @@ private record Exchange(String method, String path, String body) { } private final List exchanges = new ArrayList<>(); - private final ServerApiService service = new ServerApiService(Duration.ofHours(6)); + private final List authorizations = new ArrayList<>(); + private volatile Optional token = Optional.of("secret-token"); + private final ServerApiService service = new ServerApiService(Duration.ofHours(6), url -> token, ServerTls.defaults()); private HttpServer server; private String serverUrl; private int status = 200; private String response = "{}"; private Duration delay = Duration.ZERO; + private String location; private final CountDownLatch release = new CountDownLatch(1); @BeforeEach @@ -64,6 +74,76 @@ void stopServer() { server.stop(0); } + @Test + void tellsListenersWhichServerRejectedTheToken() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + status = 401; + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + + assertEquals(List.of(serverUrl), rejected); + } + + @Test + void doesNotTellListenersWhenNoTokenIsStored() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + token = Optional.empty(); + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + + assertEquals(List.of(), rejected); + } + + @Test + void savesADownloadOwnerOnly(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) throws Exception { + response = "PK\u0003\u0004zip"; + java.nio.file.Path destination = tempDir.resolve("fresh").resolve("b1.zip"); + + service.downloadById(serverUrl, "b1", destination, null); + + if (java.nio.file.Files.getFileStore(destination).supportsFileAttributeView("posix")) { + assertEquals("rw-------", java.nio.file.attribute.PosixFilePermissions.toString(java.nio.file.Files.getPosixFilePermissions(destination))); + assertEquals("rwx------", java.nio.file.attribute.PosixFilePermissions.toString(java.nio.file.Files.getPosixFilePermissions(destination.getParent()))); + } + } + + @Test + void aStalledDownloadFailsAndLeavesNoPartFile(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) throws Exception { + server.createContext("/api/v1/backups/stall/download", exchange -> { + exchange.sendResponseHeaders(200, 100); + OutputStream out = exchange.getResponseBody(); + out.write("PK\u0003\u0004".getBytes(StandardCharsets.UTF_8)); + out.flush(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + exchange.close(); + }); + ServerApiService stalling = new ServerApiService(Duration.ofHours(6), Duration.ofMillis(300), url -> token, ServerTls.defaults()); + java.nio.file.Path destination = tempDir.resolve("stall.zip"); + + DownloadFailedException e = assertThrows(DownloadFailedException.class, () -> stalling.downloadById(serverUrl, "stall", destination, null)); + + assertTrue(e.getMessage().contains("stopped sending data")); + try (var files = java.nio.file.Files.list(tempDir)) { + assertEquals(List.of(), files.toList()); + } + stalling.shutdown(); + } + + @Test + void aFailedDownloadMessageDoesNotLeakThePath(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tempDir) { + response = "not a zip"; + + DownloadFailedException e = assertThrows(DownloadFailedException.class, () -> service.downloadById(serverUrl, "b1", tempDir.resolve("b1.zip"), null)); + + assertFalse(e.getMessage().contains(tempDir.toString())); + } + @Test void sendsConfigUpdatesWithOmittedFieldsAsNull() { response = "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": \"PT6H\"}"; @@ -85,6 +165,56 @@ void readsTheServerVersionStatusAndIgnoresUnknownFields() { assertEquals(new Exchange("GET", "/api/v1/version", ""), exchanges.getFirst()); } + @Test + void readsTheWebhookStatusAndTestFromTheServerPayloads() { + response = Fixtures.read("server/webhook-status.json"); + assertEquals(new WebhookStatusDto(true, "https://discord.com"), service.webhook(serverUrl)); + response = Fixtures.read("server/webhook-test.json"); + assertEquals(new WebhookTestDto(false, 404, "Webhook answered 404"), service.testWebhook(serverUrl)); + + assertEquals(new Exchange("GET", "/api/v1/notifications/webhook", ""), exchanges.get(0)); + assertEquals(new Exchange("POST", "/api/v1/notifications/webhook/test", ""), exchanges.get(1)); + assertEquals(List.of("Bearer secret-token", "Bearer secret-token"), authorizations); + } + + @Test + void sendsTheWebhookUrlAndClearsItWithAnEmptyString() { + response = Fixtures.read("server/webhook-status.json"); + + service.updateWebhook(serverUrl, "https://discord.com/api/webhooks/1/abc"); + service.updateWebhook(serverUrl, ""); + + assertEquals(new Exchange("PUT", "/api/v1/notifications/webhook", "{\"url\":\"https://discord.com/api/webhooks/1/abc\"}"), exchanges.get(0)); + assertEquals(new Exchange("PUT", "/api/v1/notifications/webhook", "{\"url\":\"\"}"), exchanges.get(1)); + } + + @Test + void theWebhookUrlIsNotWrittenToTheLog() { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + ch.qos.logback.core.read.ListAppender logs = new ch.qos.logback.core.read.ListAppender<>(); + logs.start(); + root.addAppender(logs); + try { + response = Fixtures.read("server/webhook-status.json"); + service.updateWebhook(serverUrl, "https://discord.com/api/webhooks/1/SECRETTOKEN"); + service.testWebhook(serverUrl); + } finally { + root.detachAppender(logs); + } + + assertTrue(logs.list.stream().noneMatch(event -> event.getFormattedMessage().contains("SECRETTOKEN"))); + } + + @Test + void aServerRejectionOfTheWebhookKeepsItsStatusAndMessage() { + status = 429; + response = "{\"error\":\"Wait 7 seconds before sending another test\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.testWebhook(serverUrl)); + + assertEquals(429, e.getStatusCode().value()); + } + @Test void sendsScheduleAsIsoDuration() { response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H30M\"}"; @@ -129,9 +259,41 @@ void fallsBackToTheStatusWhenTheServerSendsNoMessage() { assertEquals(Map.of("error", "MediaGarrd server responded with 502"), new ApiExceptionHandler().serverRejected(e).getBody()); } + @Test + void aFailedBackupRunCarriesTheServersReasonToTheDashboard() { + status = 500; + response = "{\"error\": \"Backup of radarr failed: disk is full\"}"; + + BackupRunFailedException e = assertThrows(BackupRunFailedException.class, () -> service.triggerBackup(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().backupRunFailed(e); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, forwarded.getStatusCode()); + assertEquals(Map.of("error", "Backup of radarr failed: disk is full"), forwarded.getBody()); + } + + @Test + void aFailedBackupRunWithoutAReasonFallsBackToTheStatus() { + status = 500; + response = "oops"; + + BackupRunFailedException e = assertThrows(BackupRunFailedException.class, () -> service.triggerBackup(serverUrl)); + + assertEquals("MediaGarrd server responded with 500", e.getMessage()); + } + + @Test + void everyOtherServerFailureKeepsTheGenericText() { + status = 500; + response = "{\"error\": \"Disk /srv/backups is full\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.listBackups(serverUrl)); + + assertEquals(Map.of("error", "MediaGarrd server responded with 500"), new ApiExceptionHandler().serverRejected(e).getBody()); + } + @Test void reportsABackupRunThatOutlastsTheTimeout() { - ServerApiService shortTimeout = new ServerApiService(Duration.ofMillis(200)); + ServerApiService shortTimeout = new ServerApiService(Duration.ofMillis(200), url -> token, ServerTls.defaults()); delay = Duration.ofSeconds(2); BackupRunTimeoutException e = assertThrows(BackupRunTimeoutException.class, () -> shortTimeout.triggerBackup(serverUrl)); @@ -143,15 +305,6 @@ void reportsABackupRunThatOutlastsTheTimeout() { 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); @@ -159,26 +312,228 @@ void rejectsABackupRunTimeoutBelowTheMinimum() { assertRejected(Duration.ZERO); IllegalStateException e = assertRejected(Duration.ofSeconds(59)); assertTrue(e.getMessage().contains("at least PT1M")); - Configuration ok = new Configuration(); + MediaGarrdProperties ok = new MediaGarrdProperties(); ok.setBackupRunTimeout(Duration.ofMinutes(1)); - new ServerApiService(ok); + new ServerApiService(ok, mock(ClientStateService.class), ServerTls.defaults()); } private static IllegalStateException assertRejected(Duration timeout) { - Configuration properties = new Configuration(); + MediaGarrdProperties properties = new MediaGarrdProperties(); properties.setBackupRunTimeout(timeout); - return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties)); + return assertThrows(IllegalStateException.class, () -> new ServerApiService(properties, mock(ClientStateService.class), ServerTls.defaults())); } @Test void mapsAReadTimeoutOnTheOrdinaryClientsToGatewayTimeout() { - delay = Duration.ofSeconds(8); - ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health(serverUrl)); + ServerApiService impatient = new ServerApiService(Duration.ofHours(6), Duration.ofSeconds(60), Duration.ofMillis(200), Duration.ofMillis(200), url -> token, ServerTls.defaults()); + delay = Duration.ofSeconds(3); + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> impatient.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 sendsTheBearerTokenOnEveryAuthenticatedCall() { + ServiceDto radarr = new ServiceDto("radarr", List.of()); + + response = "[]"; + service.listBackups(serverUrl); + service.listServices(serverUrl); + response = "{\"name\": \"radarr\", \"paths\": []}"; + service.triggerBackup(serverUrl); + service.serverConfig(serverUrl); + service.updateServerConfig(serverUrl, "/b", 3); + service.updateServerSchedule(serverUrl, Duration.ofHours(1)); + service.addService(serverUrl, radarr); + service.updateService(serverUrl, "radarr", radarr); + status = 204; + service.removeService(serverUrl, "radarr"); + service.revokeClient(serverUrl, "abc"); + + assertEquals(10, authorizations.size()); + assertTrue(authorizations.stream().allMatch("Bearer secret-token"::equals), authorizations.toString()); + } + + @Test + void sendsTheTokenOnHealthOnlyWhenPairedAndNeverOnTheVersion() { + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H\"}"; + + service.health(serverUrl); + token = Optional.empty(); + service.health(serverUrl); + token = Optional.of("secret-token"); + service.serverVersion(serverUrl); + + assertEquals(List.of("Bearer secret-token", "null", "null"), authorizations); + } + + @Test + void doesNotCallTheServerOnAnAuthenticatedRequestWithoutAToken() { + token = Optional.empty(); + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.downloadById(serverUrl, "b1", java.nio.file.Path.of("/nonexistent/x.zip"), null)); + + assertTrue(exchanges.isEmpty()); + } + + @Test + void turnsAServer401IntoPairingRequiredForEveryKindOfCall(@org.junit.jupiter.api.io.TempDir java.nio.file.Path dir) { + status = 401; + response = "{\"error\": \"Invalid or revoked token\"}"; + + assertThrows(PairingRequiredException.class, () -> service.listBackups(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.health(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.triggerBackup(serverUrl)); + assertThrows(PairingRequiredException.class, () -> service.downloadById(serverUrl, "b1", dir.resolve("b.zip"), null)); + PairingRequiredException e = assertThrows(PairingRequiredException.class, () -> service.createPairingCode(serverUrl)); + ResponseEntity forwarded = new ApiExceptionHandler().pairingRequired(e); + + assertEquals(HttpStatus.BAD_GATEWAY, forwarded.getStatusCode()); + assertEquals("required", ((Map) forwarded.getBody()).get("pairing")); + } + + @Test + void doesNotFollowARedirectAndNamesWhereItPointed() { + status = 301; + location = "https://mediagarrd.example.com/api/v1/backups"; + + ServerRedirectException e = assertThrows(ServerRedirectException.class, () -> service.listBackups(serverUrl)); + + assertEquals("https://mediagarrd.example.com/api/v1/backups", e.location()); + assertTrue(e.getMessage().contains("https://mediagarrd.example.com/api/v1/backups")); + assertEquals(1, exchanges.size()); + assertEquals(HttpStatus.BAD_GATEWAY, new ApiExceptionHandler().serverRedirected(e).getStatusCode()); + } + + @Test + void doesNotFollowARedirectOnADownloadEither(@org.junit.jupiter.api.io.TempDir java.nio.file.Path dir) { + status = 302; + location = "https://elsewhere.example.com/download"; + + assertThrows(ServerRedirectException.class, () -> service.downloadById(serverUrl, "b1", dir.resolve("b.zip"), null)); + + assertEquals(1, exchanges.size()); + assertEquals(List.of("Bearer secret-token"), authorizations); + } + + @Test + void pairsWithoutATokenAndKeepsTheTokenOutOfTheLog() { + token = Optional.empty(); + response = "{\"token\": \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG\", \"id\": \"0123456789abcdef\", \"name\": \"Home\"}"; + + StoredPairing pairing = service.pair(serverUrl, "123456", "Home"); + + assertEquals("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG", pairing.token()); + assertEquals("0123456789abcdef", pairing.id()); + assertFalse(pairing.toString().contains("abcdefghij")); + assertEquals(new Exchange("POST", "/api/v1/pair", "{\"pin\":\"123456\",\"name\":\"Home\"}"), exchanges.getFirst()); + assertEquals("null", authorizations.getFirst()); + } + + @Test + void aWrongPinIsABadRequestNotAPairingRequiredSignal() { + token = Optional.empty(); + status = 401; + response = "{\"error\": \"Invalid PIN\"}"; + + InvalidRequestException e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", "Home")); + + assertEquals("Invalid PIN", e.getMessage()); + } + + @Test + void passesOnWhyPairingIsClosedOrLocked() { + token = Optional.empty(); + status = 429; + response = "{\"error\": \"Too many attempts\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.pair(serverUrl, "000000", "Home")); + + assertEquals(Map.of("error", "Too many attempts"), new ApiExceptionHandler().serverRejected(e).getBody()); + assertEquals(HttpStatus.TOO_MANY_REQUESTS, new ApiExceptionHandler().serverRejected(e).getStatusCode()); + } + + @Test + void confirmsAPairingWithTheNewTokenAndNotTheStoredOne() { + token = Optional.of("stored-token"); + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H\"}"; + + service.confirmPairing(serverUrl, "new-token"); + + assertEquals(new Exchange("GET", "/api/v1/health", ""), exchanges.getFirst()); + assertEquals(List.of("Bearer new-token"), authorizations); + } + + @Test + void aPublicOnlyHealthReplyIsNotAConfirmation() { + response = "{\"healthy\": true, \"backupInterval\": \"PT1H\"}"; + + ConfirmationRefusedException e = assertThrows(ConfirmationRefusedException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("did not confirm"), e.getMessage()); + } + + @Test + void aRefusedConfirmationIsABadRequestAndDoesNotTellListenersTheStoredTokenFailed() { + List rejected = new ArrayList<>(); + service.addTokenRejectedListener(rejected::add); + status = 401; + response = "{\"error\": \"nope\"}"; + + InvalidRequestException e = assertThrows(InvalidRequestException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("did not accept this pairing"), e.getMessage()); + assertTrue(rejected.isEmpty()); + } + + @Test + void aServerErrorOnConfirmationIsAnUpstreamFailure() { + status = 500; + response = "{\"error\": \"Internal error\"}"; + + UpstreamResponseException e = assertThrows(UpstreamResponseException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains("500"), e.getMessage()); + assertEquals(1, exchanges.size()); + } + + @Test + void gatewayStatusesOnConfirmationAreMarkedRetryable() { + for (int gateway : new int[] {502, 503, 504}) { + exchanges.clear(); + status = gateway; + response = "{}"; + + ConfirmationUnavailableException e = assertThrows(ConfirmationUnavailableException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertTrue(e.getMessage().contains(String.valueOf(gateway)), e.getMessage()); + } + } + + @Test + void aRedirectOnConfirmationIsRefused() { + status = 302; + location = "http://127.0.0.1:1/api/v1/health"; + + assertThrows(ServerRedirectException.class, () -> service.confirmPairing(serverUrl, "new-token")); + + assertEquals(1, exchanges.size()); + } + + @Test + void readsAPairingCode() { + response = "{\"code\": \"ABCDE-FGHJK\", \"expiresAt\": \"2026-11-19T12:10:00Z\"}"; + + PairingCodeDto code = service.createPairingCode(serverUrl); + + assertEquals("ABCDE-FGHJK", code.code()); + assertEquals(Instant.parse("2026-11-19T12:10:00Z"), code.expiresAt()); + assertEquals(new Exchange("POST", "/api/v1/pairing-codes", ""), exchanges.getFirst()); + assertEquals(1, exchanges.size()); + } + @Test void survivesACyclicCauseChain() { Exception a = new Exception("a"); @@ -194,6 +549,9 @@ void mapsAConnectionRefusedToBadGateway() { ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> service.health("http://127.0.0.1:1")); assertEquals(HttpStatus.BAD_GATEWAY, new ApiExceptionHandler().serverUnreachable(e).getStatusCode()); + RuntimeException backupRun = assertThrows(RuntimeException.class, () -> service.triggerBackup("http://127.0.0.1:1")); + assertInstanceOf(ResourceAccessException.class, backupRun); + assertFalse(backupRun instanceof BackupRunTimeoutException); } @Test @@ -205,14 +563,10 @@ void treatsAConnectTimeoutAsATimeoutButNotAsAReadTimeout() { 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)); + authorizations.add(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization"))); try { release.await(delay.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { @@ -220,6 +574,9 @@ private void handle(HttpExchange exchange) throws IOException { } byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (location != null) { + exchange.getResponseHeaders().add("Location", location); + } if (status == 204) { exchange.sendResponseHeaders(204, -1); } else { diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java index af19981..462bf83 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -27,6 +27,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; @@ -37,10 +38,10 @@ import org.junit.jupiter.params.provider.CsvSource; import org.springframework.scheduling.annotation.Scheduled; -import com.fasterxml.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; @Timeout(10) @@ -48,9 +49,9 @@ class ServerDiscoveryServiceTest { private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; - private final Configuration configuration = new Configuration(); + private final MediaGarrdProperties configuration = new MediaGarrdProperties(); private final ClientStateService state = mock(ClientStateService.class); - private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, new ObjectMapper()); + private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults()); private HttpServer mediaGarrd; private HttpServer otherApp; @@ -88,32 +89,15 @@ void scansEveryPortWhenTheGivenPortIsNotAMediaGarrdServer() { assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 15, "full port scan took too long"); } - @Test - void preferredServerIsResolvedFromConfiguration() { - configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); - - assertEquals(Optional.of("http://localhost:" + port(mediaGarrd)), discovery.resolvePreferredServer()); - } - @Test void connectsThePreferredServerOnlyWhileNoneIsSelected() { - configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); discovery.connectPreferredServer(); when(state.getActiveServer()).thenReturn("http://other:38471"); discovery.connectPreferredServer(); - 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() + "')"); + verify(state, times(1)).setActiveServerIfBlank("http://localhost:" + port(mediaGarrd)); } @Test @@ -141,9 +125,10 @@ void keepsRetryingUntilThePreferredServerComesUp() throws IOException { void abandonsAHangingResolveAtTheDeadlineAndNeverOverlapsAttempts() throws InterruptedException { CountDownLatch release = new CountDownLatch(1); AtomicInteger attempts = new AtomicInteger(); + AtomicBoolean resolveFinished = new AtomicBoolean(); ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); Duration deadline = Duration.ofMillis(300); - ServerDiscoveryService hanging = new ServerDiscoveryService(configuration, state, new ObjectMapper(), pool, deadline) { + ServerDiscoveryService hanging = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), pool, deadline) { @Override public Optional resolvePreferredServer() { attempts.incrementAndGet(); @@ -154,14 +139,13 @@ public Optional resolvePreferredServer() { } catch (InterruptedException ignored) { } } + resolveFinished.set(true); 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"); + assertFalse(resolveFinished.get(), "the tick waited for the hanging resolve instead of abandoning it at the deadline"); hanging.connectPreferredServer(); hanging.connectPreferredServer(); @@ -214,7 +198,7 @@ public boolean awaitTermination(long timeout, TimeUnit unit) { return true; } }; - ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, new ObjectMapper(), deferred, Duration.ofMillis(100)); + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults(), deferred, Duration.ofMillis(100)); service.connectPreferredServer(); assertEquals(1, queued.size()); @@ -280,7 +264,7 @@ void listsTheHostsOfTheLocalSubnet(int prefix, int count, String first, String l @ParameterizedTest @CsvSource(value = {"192.168.1.5, 192.168.1.5, null", "192.168.1.5:9000, 192.168.1.5, 9000", "http://server:38471/, server, 38471", "[::1]:8080, ::1, 8080"}, nullValues = "null") void parsesHostsWithOptionalPorts(String input, String host, Integer port) { - assertEquals(new HostInput(host, port), ServerDiscoveryService.parseHost(input)); + assertEquals(new HostInput("http", host, port), ServerDiscoveryService.parseHost(input)); } @Test @@ -317,4 +301,56 @@ private static int port(HttpServer server) { private static String url(HttpServer server) { return "http://127.0.0.1:" + port(server); } + + @ParameterizedTest + @CsvSource(value = {"https://garrd.example.com, garrd.example.com, null", "https://garrd.example.com:8443/, garrd.example.com, 8443", "HTTPS://Host, Host, null"}, nullValues = "null") + void keepsTheHttpsSchemeOfAnAddress(String input, String host, Integer port) { + HostInput parsed = ServerDiscoveryService.parseHost(input); + + assertEquals(new HostInput("https", host, port), parsed); + assertTrue(parsed.https()); + } + + @Test + void anHttpsCandidateOmitsTheDefaultPort() { + assertEquals("https://garrd.example.com", new ServerDiscoveryService.Candidate("https", "garrd.example.com", null, 443).url()); + assertEquals("https://garrd.example.com:8443", new ServerDiscoveryService.Candidate("https", "garrd.example.com", null, 8443).url()); + assertEquals("http://10.0.0.5:80", new ServerDiscoveryService.Candidate("10.0.0.5", null, 80).url()); + } + + @Test + void anHttpsAddressWithoutAPortIsProbedExactlyOnceOnPort443() { + List probed = new java.util.concurrent.CopyOnWriteArrayList<>(); + ServerDiscoveryService service = new ServerDiscoveryService(configuration, state, JsonMapper.builder().build(), ServerTls.defaults()) { + @Override + boolean isMediaGarrdServer(Candidate candidate) { + probed.add(candidate.url()); + return true; + } + }; + + assertEquals(java.util.Optional.of("https://127.0.0.1"), service.resolveServerByIp("https://127.0.0.1", null)); + assertEquals(java.util.Optional.of("https://127.0.0.1:8443"), service.resolveServerByIp("https://127.0.0.1:8443", null)); + assertEquals(java.util.Optional.of("https://127.0.0.1:9443"), service.resolveServerByIp("https://127.0.0.1", 9443)); + + assertEquals(List.of("https://127.0.0.1", "https://127.0.0.1:8443", "https://127.0.0.1:9443"), probed); + } + + @Test + void anHttpsPreferredServerIsProbedOnce() { + MediaGarrdProperties https = new MediaGarrdProperties(); + https.setPreferredServerIp("https://127.0.0.1"); + List probed = new java.util.concurrent.CopyOnWriteArrayList<>(); + ServerDiscoveryService service = new ServerDiscoveryService(https, state, JsonMapper.builder().build(), ServerTls.defaults()) { + @Override + boolean isMediaGarrdServer(Candidate candidate) { + probed.add(candidate.url()); + return false; + } + }; + + assertTrue(service.resolvePreferredServer().isEmpty()); + + assertEquals(List.of("https://127.0.0.1"), probed); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java index fb8dd88..6f645da 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerEventStreamServiceTest.java @@ -6,11 +6,8 @@ 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.doAnswer; 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; @@ -24,12 +21,16 @@ 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.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -38,17 +39,17 @@ 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 tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; 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) @@ -56,7 +57,7 @@ class ServerEventStreamServiceTest { private static final ObjectMapper MAPPER = JsonMapper.builder() .findAndAddModules() - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS, DateTimeFeature.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); @@ -71,12 +72,14 @@ static final class FakeServer { final BlockingQueue connections = new LinkedBlockingQueue<>(); final AtomicInteger count = new AtomicInteger(); final CountDownLatch release = new CountDownLatch(1); + final List authorizations = new CopyOnWriteArrayList<>(); 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(); + authorizations.add(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization"))); connections.add(System.nanoTime()); try { behavior.handle(exchange, connection); @@ -110,32 +113,28 @@ void stop() { Path tempDir; private ClientStateService state; - private ClientEventBroadcaster broadcaster; + private RecordingPublisher publisher; private DashboardService dashboard; private ServerApiService serverApi; private ExecutorService refreshes; private ServerEventStreamService service; - private RecordingEmitter browser; + private RecordingPublisher browser; private final List servers = new ArrayList<>(); @BeforeEach void setUp() { - Configuration configuration = new Configuration(); + MediaGarrdProperties configuration = new MediaGarrdProperties(); 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); + publisher = new RecordingPublisher(); 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()); + dashboard = new DashboardService(state, publisher, serverApi, new VersionService(updateCheck, serverApi), updateCheck, MAPPER, refreshes, Clock.systemUTC()); } @AfterEach @@ -143,11 +142,15 @@ void tearDown() { if (service != null) { service.shutdown(); } - broadcaster.shutdown(); refreshes.shutdownNow(); servers.forEach(FakeServer::stop); } + private void activate(String url) { + state.storePairing(url, new StoredPairing("test-token", "abc", "Test")); + state.setActiveServer(url); + } + private FakeServer fake(Behavior behavior) throws IOException { FakeServer fake = new FakeServer(behavior); servers.add(fake); @@ -155,8 +158,8 @@ private FakeServer fake(Behavior behavior) throws IOException { } private void startService(Timing timing) { - service = new ServerEventStreamService(state, dashboard, MAPPER, timing); - browser = (RecordingEmitter) dashboard.subscribe().orElseThrow(); + service = new ServerEventStreamService(state, dashboard, MAPPER, ServerTls.defaults(), timing); + browser = dashboard.subscribe(publisher::subscribe).orElseThrow(); service.start(); } @@ -215,29 +218,80 @@ void forwardsRunEventsAndIgnoresEverythingElse() throws Exception { frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\",\"startedAt\":\"t1\",\"finishedAt\":\"t2\"}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(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 relevant = seen.stream().filter(event -> !nameOf(event).equals("versions") && !isLink(event, "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\"")); + assertTrue(dataOf(relevant.get(0)).path("activeServer").isNull()); + assertEquals(fake.url(), dataOf(relevant.get(1)).path("activeServer").asString()); + assertEquals("CONNECTING", dataOf(relevant.get(1)).path("link").asString()); + assertEquals("LIVE", dataOf(relevant.get(2)).path("state").asString()); + assertEquals(fake.url(), dataOf(relevant.get(2)).path("server").asString()); + assertEquals("t1", dataOf(relevant.get(4)).path("startedAt").asString()); + assertEquals("t3", dataOf(relevant.get(5)).path("at").asString()); + assertEquals("PARTIAL", dataOf(relevant.get(6)).path("status").asString()); + } + + @Test + void switchingBetweenTwoUnpairedKnownServersUpdatesTheDashboard() throws InterruptedException { + dashboard.start(); + state.updateKnownServers(List.of("http://unpaired-a:38471", "http://unpaired-b:38471")); + startService(FAST); + assertEquals("http://unpaired-a:38471", dashboard.state().activeServer()); + + state.setActiveServer("http://unpaired-b:38471"); + + assertEquals("http://unpaired-b:38471", dashboard.state().activeServer()); + String snapshot = browser.nextContaining("\"activeServer\":\"http://unpaired-b:38471\""); + assertEquals("snapshot", nameOf(snapshot)); + } + + @Test + void forwardsEventDataAsOneLineSoItCannotInjectFields() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + OutputStream out = open(exchange); + frame(out, "event: backups-changed\ndata: {\"at\":\ndata: \"t3\",\ndata: \"x\":\"y\"}\n\n"); + frame(out, "event:run-finished\ndata:{\"running\":false,\"status\":\"OK\"}\n\n"); + hold(); + }); + activate(fake.url()); + + startService(FAST); + + List seen = collectUntil("event:run-finished"); + String changed = seen.stream().filter(event -> nameOf(event).equals("backups-changed")).findFirst().orElseThrow(); + assertEquals(List.of("event:backups-changed", "data:{\"at\":\"t3\",\"x\":\"y\"}"), changed.lines().filter(line -> !line.isEmpty()).toList()); } private static String nameOf(String event) { - for (String line : event.split("\n")) { - if (line.startsWith("event:")) { - return line.substring("event:".length()); + return RecordingPublisher.eventName(event); + } + + private static JsonNode dataOf(String event) { + return RecordingPublisher.data(event); + } + + private static boolean isLink(String event, String state) { + return nameOf(event).equals("link") && state.equals(dataOf(event).path("state").asString()); + } + + private String awaitLink(String state) throws InterruptedException { + while (true) { + String event = browser.next(); + if (isLink(event, state)) { + return event; } } - return ""; + } + + private static List streamThreads() { + return Thread.getAllStackTraces().keySet().stream() + .filter(thread -> thread.isAlive() && thread.getName().startsWith("server-event-stream-")) + .toList(); } private static void hold() throws Exception { @@ -253,7 +307,7 @@ void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exceptio hold(); } }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); @@ -262,33 +316,42 @@ void reconnectsRightAwayAfterACleanEndWithoutFlickeringTheLink() throws Exceptio 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\"")) { + if (isLink(seen.get(i), "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\""))); + assertTrue(seen.subList(connectedAt, seen.size()).stream().noneMatch(event -> isLink(event, "DOWN"))); } @Test void retriesWithBackoffAfterAFailureAndReportsTheLinkDown() throws Exception { + CountDownLatch allowStream = new CountDownLatch(1); FakeServer fake = fake((exchange, connection) -> { if (connection < 3) { exchange.sendResponseHeaders(500, -1); return; } + allowStream.await(10, TimeUnit.SECONDS); OutputStream out = open(exchange); frame(out, "event: state\ndata: {\"running\":true}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); + long first = fake.awaitConnection(); + long second = fake.awaitConnection(); + long third = fake.awaitConnection(); + awaitLink("DOWN"); + allowStream.countDown(); List seen = collectUntil("event:state"); assertEquals(3, fake.count.get()); - assertTrue(seen.stream().anyMatch(event -> event.contains("event:link") && event.contains("\"state\":\"LIVE\""))); + assertTrue(TimeUnit.NANOSECONDS.toMillis(second - first) >= 20, "first retry came before the initial backoff"); + assertTrue(TimeUnit.NANOSECONDS.toMillis(third - second) >= 40, "second retry came before the doubled backoff"); + assertTrue(seen.stream().anyMatch(event -> isLink(event, "LIVE"))); } @Test @@ -304,12 +367,12 @@ void rejectsAResponseThatIsNotAnEventStream() throws Exception { frame(out, "event: state\ndata: {\"running\":false}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); List seen = collectUntil("event:state"); - assertTrue(seen.get(seen.size() - 1).contains("\"running\":false")); + assertFalse(dataOf(seen.get(seen.size() - 1)).path("running").asBoolean(true)); assertEquals(2, fake.count.get()); } @@ -324,7 +387,7 @@ void anOldServerWithoutTheStreamIsRetriedOnlyAfterTheLongInterval() throws Excep frame(out, "event: state\ndata: {\"running\":false}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(FAST); @@ -339,16 +402,17 @@ void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Ex 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()); + activate(old.url()); startService(FAST); collectUntil("\"running\":true"); - state.setActiveServer(next.url()); + activate(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()))); + assertTrue(seen.stream().anyMatch(event -> nameOf(event).equals("snapshot") + && next.url().equals(dataOf(event).path("activeServer").asString()) && dataOf(event).path("running").isNull())); + assertTrue(seen.stream().anyMatch(event -> isLink(event, "LIVE") && next.url().equals(dataOf(event).path("server").asString()))); assertEquals(1, old.count.get()); } @@ -356,7 +420,7 @@ void movingToAnotherServerClosesTheOldStreamAndSubscribesToTheNewOne() throws Ex 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()); + activate(fake.url()); startService(FAST); collectUntil("\"running\":true"); @@ -364,7 +428,8 @@ void clearingTheActiveServerStopsTheStreamAndDoesNotReconnect() throws Exception assertTrue(closed.await(10, TimeUnit.SECONDS)); String cleared = browser.nextContaining("\"activeServer\":null"); - assertTrue(cleared.contains("event:snapshot") && cleared.contains("\"link\":\"DOWN\""), cleared); + assertEquals("snapshot", nameOf(cleared)); + assertEquals("DOWN", dataOf(cleared).path("link").asString(), cleared); assertEquals(1, fake.count.get()); } @@ -373,8 +438,10 @@ 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)); + assertEquals("snapshot", nameOf(snapshot)); + assertEquals("DOWN", dataOf(snapshot).path("link").asString()); + assertTrue(streamThreads().isEmpty()); + assertNull(browser.sent.poll()); } @Test @@ -385,21 +452,27 @@ void reconnectsAStreamThatGoesSilent() throws Exception { frame(out, "event: state\ndata: {\"running\":" + (connection == 1) + "}\n\n"); hold(); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(quick); fake.awaitConnection(); fake.awaitConnection(); List seen = collectUntil("\"running\":false"); - assertFalse(seen.isEmpty()); + List linkStates = seen.stream().filter(event -> nameOf(event).equals("link")).map(event -> dataOf(event).path("state").asString()).toList(); + int firstLive = linkStates.indexOf("LIVE"); + assertTrue(firstLive >= 0, "the first connection never went live: " + linkStates); + List afterwards = linkStates.subList(firstLive + 1, linkStates.size()); + assertEquals("LIVE", afterwards.getLast(), "the link did not come back after the silence: " + linkStates); + assertTrue(afterwards.stream().anyMatch(state -> !state.equals("LIVE")), "the silent stream was never reported as lost: " + linkStates); + assertEquals(2, fake.count.get()); } @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(); + activate(fake.url()); + MediaGarrdProperties configuration = new MediaGarrdProperties(); configuration.setStateFile(tempDir.resolve("state.json").toString()); configuration.setPickupInterval(Duration.ofHours(12)); state = new ClientStateService(configuration, MAPPER); @@ -417,7 +490,7 @@ void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() thro OutputStream out = open(exchange); frame(out, "event: state\ndata: {\"running\":false}\n\n"); }); - state.setActiveServer(fake.url()); + activate(fake.url()); startService(slowRetry); @@ -429,23 +502,292 @@ void aStreamThatEndsRightAfterOpeningIsRetriedWithBackoffInsteadOfInALoop() thro } @Test - void aConfigChangedEventMakesTheClientRefetchTheServerHealthOnce() throws Exception { - doReturn(new ServerStatusDto(true, false, 5, Duration.ofHours(6))).when(serverApi).health(anyString()); + void severalConfigChangedEventsDuringARefreshAreCoalescedIntoOneMoreFetch() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + CountDownLatch firstFetchStarted = new CountDownLatch(1); + CountDownLatch finishFetch = new CountDownLatch(1); + doAnswer(invocation -> { + fetches.incrementAndGet(); + firstFetchStarted.countDown(); + finishFetch.await(10, TimeUnit.SECONDS); + return new ServerStatusDto(true, false, 5, Duration.ofHours(6)); + }).when(serverApi).health(anyString()); + CountDownLatch burst = new CountDownLatch(1); 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"); + burst.await(10, TimeUnit.SECONDS); + for (int i = 0; i < 3; i++) { + frame(out, "event: config-changed\ndata: {\"at\":\"t" + i + "\"}\n\n"); + } + frame(out, "event: state\ndata: {\"running\":true}\n\n"); hold(); }); + activate(fake.url()); + + startService(FAST); + + assertTrue(firstFetchStarted.await(10, TimeUnit.SECONDS)); + awaitLink("LIVE"); + burst.countDown(); + browser.nextContaining("\"running\":true"); + assertEquals(1, fetches.get(), "no fetch may start while the first one is still in flight"); + finishFetch.countDown(); + refreshes.submit(() -> { }).get(10, TimeUnit.SECONDS); + + assertEquals(2, fetches.get(), "the burst of config-changed events must cost exactly one more fetch"); + } + + @Test + void sendsTheBearerTokenWhenSubscribing() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1), "event: state\ndata: {\"running\":true}\n\n")); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + assertEquals("Bearer test-token", fake.authorizations.getFirst()); + } + + @Test + void aRejectedTokenStopsTheStreamInsteadOfRetrying() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + exchange.sendResponseHeaders(401, -1); + }); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + awaitRejected(); + assertEquals(1, fake.count.get()); + assertEquals(wellatleastitried.mediagarrdclient.dto.PairingState.REJECTED, dashboard.state().pairing()); + } + + @Test + void pairingAgainRestartsTheStreamWithTheNewToken() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if ("Bearer test-token".equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + exchange.sendResponseHeaders(401, -1); + return; + } + OutputStream out = open(exchange); + frame(out, "event: state\ndata: {\"running\":true}\n\n"); + hold(); + }); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + + state.storePairing(fake.url(), new StoredPairing("second-token", "id2", "Test")); + + fake.awaitConnection(); + collectUntil("\"running\":true"); + assertEquals("Bearer second-token", fake.authorizations.getLast()); + } + + @Test + void doesNotConnectToAServerThatIsNotPaired() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1))); state.setActiveServer(fake.url()); startService(FAST); - browser.nextContaining("event:config"); - Thread.sleep(800); - clearInvocations(serverApi); + assertEquals("snapshot", nameOf(browser.next())); + assertTrue(streamThreads().isEmpty()); + assertEquals(0, fake.count.get()); + } + + @Test + void doesNotFollowARedirectWithTheToken() throws Exception { + FakeServer elsewhere = fake(holdOpen(new CountDownLatch(1))); + FakeServer fake = fake((exchange, connection) -> { + exchange.getResponseHeaders().add("Location", elsewhere.url() + "/api/v1/events"); + exchange.sendResponseHeaders(302, -1); + }); + activate(fake.url()); + + startService(FAST); + + fake.awaitConnection(); + fake.awaitConnection(); + assertEquals(0, elsewhere.count.get()); + } + + @Test + void recoveryRestartsARejectedStreamAgainOnceTheCoolDownHasPassed() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(Duration.ofMinutes(5).toNanos()); + service.recovered(fake.url()); + + fake.awaitConnection(); + assertEquals(3, fake.count.get()); + assertTrue(scheduler.commands.isEmpty(), "a recovery after the cool-down must restart at once, not be deferred"); + scheduler.shutdownNow(); + } + + static final class CapturingScheduler extends ScheduledThreadPoolExecutor { + + final List commands = new CopyOnWriteArrayList<>(); + final List delays = new CopyOnWriteArrayList<>(); + final List> futures = new CopyOnWriteArrayList<>(); + + CapturingScheduler() { + super(1, runnable -> { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + return thread; + }); + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + commands.add(command); + delays.add(unit.toNanos(delay)); + ScheduledFuture future = super.schedule(command, 1, TimeUnit.DAYS); + futures.add(future); + return future; + } + } + + private void startService(Timing timing, AtomicLong nanos, CapturingScheduler scheduler) { + service = new ServerEventStreamService(state, dashboard, MAPPER, ServerTls.defaults(), timing, nanos::get, scheduler); + browser = dashboard.subscribe(publisher::subscribe).orElseThrow(); + service.start(); + } + + @Test + void recoveryDuringTheCoolDownIsDeferredAndRestartsAStillRejectedStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(TimeUnit.SECONDS.toNanos(10)); + service.recovered(fake.url()); + service.recovered(fake.url()); + + assertEquals(2, fake.count.get()); + assertEquals(2, scheduler.commands.size()); + assertEquals(Duration.ofMinutes(5).minusSeconds(10).toNanos(), scheduler.delays.getLast()); + assertTrue(scheduler.futures.getFirst().isCancelled()); + + nanos.addAndGet(Duration.ofMinutes(5).toNanos()); + scheduler.commands.getLast().run(); + fake.awaitConnection(); + assertEquals(3, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void aDeferredRecoveryIsCancelledAndIgnoredOnceTheStreamWasReplaced() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + nanos.addAndGet(TimeUnit.SECONDS.toNanos(10)); + service.recovered(fake.url()); + assertEquals(1, scheduler.commands.size()); + + state.storePairing(fake.url(), new StoredPairing("new-token", "def", "Test")); + fake.awaitConnection(); + awaitRejected(); + + assertTrue(scheduler.futures.getFirst().isCancelled()); + nanos.addAndGet(Duration.ofMinutes(10).toNanos()); + scheduler.commands.getFirst().run(); + assertNull(fake.connections.poll(300, TimeUnit.MILLISECONDS)); + assertEquals(3, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void deferredRecoveryDoesNothingOnceTheStreamIsNoLongerRejected() throws Exception { + FakeServer fake = fake((exchange, connection) -> exchange.sendResponseHeaders(401, -1)); + activate(fake.url()); + AtomicLong nanos = new AtomicLong(1_000_000_000L); + CapturingScheduler scheduler = new CapturingScheduler(); + startService(new Timing(Duration.ofSeconds(5), Duration.ofSeconds(30), Duration.ofMillis(20), Duration.ofMillis(80), Duration.ofMinutes(5), Duration.ZERO), nanos, scheduler); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + fake.awaitConnection(); + awaitRejected(); + service.recovered(fake.url()); + assertEquals(1, scheduler.commands.size()); + + state.setActiveServer(null); + + assertTrue(scheduler.futures.getFirst().isCancelled()); + nanos.addAndGet(Duration.ofMinutes(10).toNanos()); + scheduler.commands.getFirst().run(); + assertTrue(streamThreads().isEmpty()); + assertEquals(2, fake.count.get()); + scheduler.shutdownNow(); + } + + @Test + void recoveryDoesNotRestartAStreamThatWasNotRejected() throws Exception { + FakeServer fake = fake(holdOpen(new CountDownLatch(1))); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + List before = streamThreads(); + assertEquals(1, before.size()); + + service.recovered(fake.url()); + + assertEquals(before, streamThreads(), "a restart would have replaced the stream thread"); + assertEquals(1, fake.count.get()); + } + + @Test + void recoveryOfAnotherServerDoesNotRestartARejectedStream() throws Exception { + FakeServer fake = fake((exchange, connection) -> { + if (connection == 1) { + exchange.sendResponseHeaders(401, -1); + return; + } + holdOpen(new CountDownLatch(1)).handle(exchange, connection); + }); + activate(fake.url()); + startService(FAST); + fake.awaitConnection(); + awaitRejected(); + + service.recovered("http://127.0.0.1:1"); - verify(serverApi, timeout(10_000).times(1)).health(fake.url()); + assertTrue(streamThreads().isEmpty(), "a restart would have started a stream that stays open"); + assertEquals(1, fake.count.get()); + } + + private void awaitRejected() throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!streamThreads().isEmpty()) { + assertTrue(System.nanoTime() < deadline, "the rejected stream never ended"); + Thread.sleep(10); + } } } diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java new file mode 100644 index 0000000..a35bda6 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerPayloadGoldenTest.java @@ -0,0 +1,174 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.client.RestClientResponseException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.CheckState; +import wellatleastitried.mediagarrdclient.dto.PairingCodeDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +class ServerPayloadGoldenTest { + + private final ServerApiService service = new ServerApiService(Duration.ofHours(6), url -> Optional.of("secret-token"), ServerTls.defaults()); + private HttpServer server; + private String serverUrl; + private volatile int status = 200; + private volatile String response = "{}"; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + serverUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void readsThePublicHealthPayloadWithFieldsTheServerDoesNotSend() { + response = Fixtures.read("server/health-public.json"); + + ServerStatusDto health = service.health(serverUrl); + + assertEquals(new ServerStatusDto(true, false, 0, Duration.ofHours(6)), health); + } + + @Test + void readsTheAuthenticatedHealthPayload() { + response = Fixtures.read("server/health-status.json"); + + ServerStatusDto health = service.health(serverUrl); + + assertEquals(new ServerStatusDto(true, false, 7, Duration.ofHours(12)), health); + } + + @Test + void readsTheVersionPayload() { + response = Fixtures.read("server/version.json"); + + 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-20T10:15:30.123456Z"), null), version); + } + + @Test + void readsTheBackupList() { + response = Fixtures.read("server/backups.json"); + + List backups = service.listBackups(serverUrl); + + assertEquals(List.of( + new BackupDto("backup-2026-11-20", "mediagarrd-2026-11-20.zip", 1048576L, Instant.parse("2026-11-20T10:15:30.123456Z")), + new BackupDto("backup-2026-11-19", "mediagarrd-2026-11-19.zip", 2097152L, Instant.parse("2026-11-19T04:00:00Z"))), backups); + } + + @Test + void readsTheConfigPayload() { + response = Fixtures.read("server/config.json"); + + ServerConfigDto config = service.serverConfig(serverUrl); + + assertEquals(new ServerConfigDto("/var/backups/mediagarrd", 7, Duration.ofHours(6)), config); + } + + @Test + void readsTheServiceList() { + response = Fixtures.read("server/services.json"); + + List services = service.listServices(serverUrl); + + assertEquals(List.of( + new ServiceDto("jellyfin", List.of("/srv/jellyfin/config", "/srv/jellyfin/data")), + new ServiceDto("radarr", List.of("/srv/radarr"))), services); + } + + @Test + void readsThePairResponse() { + response = Fixtures.read("server/pair-response.json"); + + StoredPairing pairing = service.pair(serverUrl, "123456", "Golden Laptop"); + + assertEquals("golden-token", pairing.token()); + assertEquals("c0ffee00-0000-4000-8000-000000000003", pairing.id()); + assertEquals("Golden Laptop", pairing.name()); + } + + @Test + void readsThePairingCode() { + response = Fixtures.read("server/pairing-code.json"); + + PairingCodeDto code = service.createPairingCode(serverUrl); + + assertEquals(new PairingCodeDto("482913", Instant.parse("2026-11-20T10:25:30.500Z")), code); + } + + @Test + void readsTheErrorMessageFromTheServerErrorShape() { + status = 401; + response = Fixtures.read("server/error-4xx.json"); + + var e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", null)); + + assertEquals("The PIN is not valid", e.getMessage()); + } + + @Test + void readsTheErrorMessageFromSpringsDefaultErrorBody() { + status = 401; + response = Fixtures.read("server/error-spring-default.json"); + + var e = assertThrows(InvalidRequestException.class, () -> service.pair(serverUrl, "000000", null)); + + assertEquals("Unauthorized", e.getMessage()); + } + + @Test + void exposesTheServerErrorBodyOfAnUnexpectedStatus() { + status = 409; + response = Fixtures.read("server/error-4xx.json"); + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.createPairingCode(serverUrl)); + + assertEquals(409, e.getStatusCode().value()); + assertTrue(e.getResponseBodyAsString().contains("The PIN is not valid")); + } + + private void handle(HttpExchange exchange) throws IOException { + exchange.getRequestBody().readAllBytes(); + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java new file mode 100644 index 0000000..06ab3be --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerTlsTest.java @@ -0,0 +1,202 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.time.Duration; +import java.util.Optional; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.client.ResourceAccessException; + +import tools.jackson.databind.json.JsonMapper; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; + +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; + +class ServerTlsTest { + + private static final char[] PASSWORD = "changeit".toCharArray(); + private static final String HEALTH = "{\"healthy\": true, \"backupInterval\": \"PT1H\"}"; + + @TempDir + Path tempDir; + + private HttpsServer server; + private Path certificate; + private String authorization; + + private void run(String... command) throws IOException, InterruptedException { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (process.waitFor() != 0) { + throw new IOException(String.join(" ", command) + " failed: " + output); + } + } + + @BeforeEach + void startHttpsServer() throws Exception { + Path keystore = tempDir.resolve("server.p12"); + certificate = tempDir.resolve("ca.pem"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "server", "-keyalg", "RSA", "-keysize", "2048", "-validity", "2", "-dname", "CN=MediaGarrd Test CA", + "-ext", "san=ip:127.0.0.1", "-ext", "bc:c", "-keystore", keystore.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "server", "-keystore", keystore.toString(), "-storepass", new String(PASSWORD), "-file", certificate.toString()); + + KeyStore store = KeyStore.getInstance("PKCS12"); + try (InputStream in = Files.newInputStream(keystore)) { + store.load(in, PASSWORD); + } + KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keys.init(store, PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keys.getKeyManagers(), null, null); + server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(context)); + server.createContext("/", exchange -> { + authorization = exchange.getRequestHeaders().getFirst("Authorization"); + byte[] body = HEALTH.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + server.start(); + } + + @AfterEach + void stopHttpsServer() { + server.stop(0); + } + + private String url() { + return "https://127.0.0.1:" + server.getAddress().getPort(); + } + + private ServerApiService api(ServerTls tls) { + return new ServerApiService(Duration.ofHours(1), serverUrl -> Optional.of("tok"), tls); + } + + @Test + void aSelfSignedServerIsRefusedWithoutTheCa() { + assertThrows(ResourceAccessException.class, () -> api(ServerTls.defaults()).health(url())); + } + + @Test + void theConfiguredCaMakesTheServerTrustedAndTheTokenTravelsOverTls() { + ServerApiService api = api(new ServerTls(certificate.toString())); + + assertTrue(api.health(url()).healthy()); + assertEquals("Bearer tok", authorization); + } + + @Test + void hostnameVerificationStaysOnEvenWithTheCa() { + String byName = "https://localhost:" + server.getAddress().getPort(); + + ResourceAccessException e = assertThrows(ResourceAccessException.class, () -> api(new ServerTls(certificate.toString())).health(byName)); + + StringBuilder chain = new StringBuilder(); + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + chain.append(cause.getClass().getSimpleName()).append(": ").append(cause.getMessage()).append('\n'); + } + assertTrue(chain.toString().contains("SSLHandshakeException"), chain.toString()); + assertTrue(api(new ServerTls(certificate.toString())).health(url()).healthy()); + } + + @Test + void anUnrelatedCaDoesNotTrustTheServer() throws Exception { + Path other = tempDir.resolve("other.p12"); + Path otherPem = tempDir.resolve("other.pem"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "o", "-keyalg", "RSA", "-keysize", "2048", "-dname", "CN=Other", "-keystore", other.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "o", "-keystore", other.toString(), "-storepass", new String(PASSWORD), "-file", otherPem.toString()); + + assertThrows(ResourceAccessException.class, () -> api(new ServerTls(otherPem.toString())).health(url())); + } + + @Test + void theDefaultTrustStillWorksWhenAnUnrelatedCaIsConfigured() throws Exception { + Path otherPem = tempDir.resolve("other.pem"); + Path other = tempDir.resolve("other.p12"); + Path systemTrust = tempDir.resolve("system-trust.p12"); + String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString(); + run(keytool, "-genkeypair", "-alias", "o", "-keyalg", "RSA", "-keysize", "2048", "-dname", "CN=Other", "-keystore", other.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + run(keytool, "-exportcert", "-rfc", "-alias", "o", "-keystore", other.toString(), "-storepass", new String(PASSWORD), "-file", otherPem.toString()); + run(keytool, "-importcert", "-noprompt", "-alias", "system-ca", "-file", certificate.toString(), "-keystore", systemTrust.toString(), "-storetype", "PKCS12", "-storepass", new String(PASSWORD)); + assertThrows(ResourceAccessException.class, () -> api(new ServerTls(otherPem.toString())).health(url())); + + String path = System.getProperty("javax.net.ssl.trustStore"); + String type = System.getProperty("javax.net.ssl.trustStoreType"); + String password = System.getProperty("javax.net.ssl.trustStorePassword"); + System.setProperty("javax.net.ssl.trustStore", systemTrust.toString()); + System.setProperty("javax.net.ssl.trustStoreType", "PKCS12"); + System.setProperty("javax.net.ssl.trustStorePassword", new String(PASSWORD)); + try { + assertTrue(api(new ServerTls(otherPem.toString())).health(url()).healthy()); + } finally { + restore("javax.net.ssl.trustStore", path); + restore("javax.net.ssl.trustStoreType", type); + restore("javax.net.ssl.trustStorePassword", password); + } + } + + private static void restore(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + @Test + void discoveryProbesAnHttpsAddressWithTheSharedTrust() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + configuration.setStateFile(tempDir.resolve("state.json").toString()); + ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, mock(ClientStateService.class), JsonMapper.builder().build(), new ServerTls(certificate.toString())); + + Optional found = discovery.resolveServerByIp(url(), null); + + assertEquals(Optional.of(url()), found); + } + + @Test + void discoveryDoesNotTrustAnUnknownCertificate() { + MediaGarrdProperties configuration = new MediaGarrdProperties(); + ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, mock(ClientStateService.class), JsonMapper.builder().build(), ServerTls.defaults()); + + assertTrue(discovery.resolveServerByIp(url(), null).isEmpty()); + } + + @Test + void anUnreadableCaFileIsAClearStartupError() { + IllegalStateException missing = assertThrows(IllegalStateException.class, () -> new ServerTls(tempDir.resolve("nope.pem").toString())); + Path junk = tempDir.resolve("junk.pem"); + try { + Files.writeString(junk, "not a certificate"); + } catch (IOException e) { + throw new IllegalStateException(e); + } + IllegalStateException invalid = assertThrows(IllegalStateException.class, () -> new ServerTls(junk.toString())); + + assertTrue(missing.getMessage().contains("MEDIAGARRD_SERVER_CA"), missing.getMessage()); + assertTrue(invalid.getMessage().contains("MEDIAGARRD_SERVER_CA"), invalid.getMessage()); + } + +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java new file mode 100644 index 0000000..7d2981b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerUrlsTest.java @@ -0,0 +1,34 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class ServerUrlsTest { + + @ParameterizedTest + @CsvSource({ + "http://server:38471, http://server:38471", + "HTTP://Server:38471/, http://server:38471", + "http://server:80, http://server", + "https://Garrd.Example.com:443/, https://garrd.example.com", + "https://garrd.example.com:8443, https://garrd.example.com:8443", + "https://garrd.example.com///, https://garrd.example.com", + "https://example.com/garrd/, https://example.com/garrd", + "http://[::1]:8080, http://[::1]:8080", + "http://user:pw@server:8080, http://server:8080" + }) + void normalizesUrls(String input, String expected) { + assertEquals(expected, ServerUrls.normalize(input)); + } + + @Test + void leavesNonUrlsAloneInsteadOfFailing() { + assertEquals("not a url", ServerUrls.normalize(" not a url/ ")); + assertEquals("", ServerUrls.normalize(" ")); + assertNull(ServerUrls.normalize(null)); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java new file mode 100644 index 0000000..770400f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServiceNamesTest.java @@ -0,0 +1,23 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class ServiceNamesTest { + + @Test + void acceptsTheNamesTheServerAccepts() { + assertEquals("radarr", ServiceNames.require("radarr")); + assertEquals("Sonarr_4k.v2-x", ServiceNames.require("Sonarr_4k.v2-x")); + assertEquals("a".repeat(64), ServiceNames.require("a".repeat(64))); + } + + @Test + void refusesNamesThatCouldChangeThePath() { + for (String name : new String[] {null, "", ".", "..", ".hidden", "a/b", "a\\b", "a b", "%2e%2e", "a".repeat(65), "x?y", "x#y"}) { + assertThrows(InvalidRequestException.class, () -> ServiceNames.require(name), String.valueOf(name)); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java new file mode 100644 index 0000000..64ad14f --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SessionServiceTest.java @@ -0,0 +1,104 @@ +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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.time.Instant; + +import org.junit.jupiter.api.Test; + +class SessionServiceTest { + + private final MutableClock clock = new MutableClock(Instant.parse("2026-11-19T12:00:00Z")); + private final SessionService sessions = new SessionService(clock, Duration.ofHours(1), Duration.ofHours(5), 3); + + @Test + void tellsListenersWhichSessionEndedOnLogoutClearAndExpiry() { + java.util.List ended = new java.util.ArrayList<>(); + sessions.addEndedListener(ended::add); + String first = sessions.create(); + String second = sessions.create(); + String third = sessions.create(); + + sessions.invalidate(first); + assertEquals(java.util.List.of(SessionService.keyOf(first)), ended); + assertFalse(sessions.validate(first)); + assertTrue(sessions.validate(third)); + sessions.invalidate(first); + assertEquals(1, ended.size()); + + clock.advance(Duration.ofHours(2)); + assertFalse(sessions.validate(second)); + assertEquals(SessionService.keyOf(second), ended.get(1)); + + sessions.clear(); + assertEquals(java.util.List.of(SessionService.keyOf(first), SessionService.keyOf(second), SessionService.keyOf(third)), ended); + assertFalse(sessions.validate(third)); + } + + @Test + void reportsWhetherASessionIsStillActiveWithoutExtendingIt() { + String token = sessions.create(); + String key = SessionService.keyOf(token); + + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.isActive(key)); + clock.advance(Duration.ofMinutes(2)); + + assertFalse(sessions.isActive(key)); + assertFalse(sessions.isActive(null)); + assertFalse(sessions.isActive("unknown")); + } + + @Test + void acceptsOnlySessionsItCreated() { + String token = sessions.create(); + + assertTrue(sessions.validate(token)); + assertFalse(sessions.validate(token + "x")); + assertFalse(sessions.validate("")); + assertFalse(sessions.validate(null)); + assertEquals(43, token.length()); + } + + @Test + void sessionsExpireAfterBeingIdle() { + String token = sessions.create(); + + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + clock.advance(Duration.ofMinutes(61)); + assertFalse(sessions.validate(token)); + } + + @Test + void sessionsExpireAfterTheAbsoluteLimitEvenWhenActive() { + String token = sessions.create(); + + for (int i = 0; i < 5; i++) { + clock.advance(Duration.ofMinutes(59)); + assertTrue(sessions.validate(token)); + } + clock.advance(Duration.ofMinutes(59)); + assertFalse(sessions.validate(token)); + } + + @Test + void keepsAtMostTheConfiguredNumberOfSessionsDroppingTheOldest() { + String a = sessions.create(); + String b = sessions.create(); + String c = sessions.create(); + String d = sessions.create(); + + assertFalse(sessions.validate(a)); + assertTrue(sessions.validate(b)); + assertTrue(sessions.validate(c)); + assertTrue(sessions.validate(d)); + assertNotEquals(b, c); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java new file mode 100644 index 0000000..7a781fa --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/SseReaderTest.java @@ -0,0 +1,97 @@ +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.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.Test; + +class SseReaderTest { + + private static List read(String stream, AtomicInteger lines) throws IOException { + List events = new ArrayList<>(); + SseReader.read(new ByteArrayInputStream(stream.getBytes(StandardCharsets.UTF_8)), lines::incrementAndGet, (name, data) -> events.add(name + "=" + data)); + return events; + } + + @Test + void reportsWhetherAnyEventWasDispatched() throws IOException { + SseReader.Handler ignore = (name, data) -> { + }; + + assertTrue(SseReader.read(new ByteArrayInputStream("data: a\n\n".getBytes(StandardCharsets.UTF_8)), () -> { + }, ignore)); + assertFalse(SseReader.read(new ByteArrayInputStream(": ping\n\ndata: unfinished".getBytes(StandardCharsets.UTF_8)), () -> { + }, ignore)); + } + + @Test + void parsesNamedAndUnnamedEventsAndMultiLineData() throws IOException { + List events = read("event: state\ndata: {\"running\":true}\n\ndata: a\ndata: b\n\n", new AtomicInteger()); + + assertEquals(List.of("state={\"running\":true}", "message=a\nb"), events); + } + + @Test + void ignoresCommentsUnknownFieldsAndEventsWithoutData() throws IOException { + List events = read(": ping\nretry: 5000\nevent: lonely\n\nevent: state\ndata:x\n\n", new AtomicInteger()); + + assertEquals(List.of("state=x"), events); + } + + @Test + void dropsAnEventThatIsNotTerminatedByABlankLine() throws IOException { + assertEquals(List.of(), read("event: state\ndata: 1\n", new AtomicInteger())); + } + + @Test + void refusesALineLongerThanTheCap() { + assertThrows(IOException.class, () -> SseReader.read(new ByteArrayInputStream(("data: " + "x".repeat(100) + "\n\n").getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> { }, 50, 1000)); + } + + @Test + void refusesAnEventLargerThanTheCapEvenWhenEveryLineIsSmall() { + String stream = "data: " + "x".repeat(30) + "\ndata: " + "y".repeat(30) + "\n\n"; + + assertThrows(IOException.class, () -> SseReader.read(new ByteArrayInputStream(stream.getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> { }, 50, 40)); + } + + @Test + void acceptsLinesAndEventsWithinTheCapsAndAllLineEndings() throws IOException { + List events = new ArrayList<>(); + + SseReader.read(new ByteArrayInputStream("event: a\r\ndata: 1\r\r\ndata: 2\n\n".getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> events.add(name + "=" + data), 50, 50); + + assertEquals(List.of("a=1", "message=2"), events); + } + + @Test + void aLargeLegitimateEventPassesTheDefaultCaps() throws IOException { + List events = new ArrayList<>(); + + SseReader.read(new ByteArrayInputStream(("event: backups-changed\ndata: " + "x".repeat(200_000) + "\n\n").getBytes(StandardCharsets.UTF_8)), + () -> { }, (name, data) -> events.add(name)); + + assertEquals(List.of("backups-changed"), events); + } + + @Test + void reportsActivityForEveryLine() throws IOException { + AtomicInteger lines = new AtomicInteger(); + + read(": a\nevent: x\ndata: 1\n\n", lines); + + assertEquals(4, lines.get()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java new file mode 100644 index 0000000..971a4fa --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFileMissingFieldsGoldenTest.java @@ -0,0 +1,80 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +class StateFileMissingFieldsGoldenTest { + + static void register(DynamicPropertyRegistry registry, Path dataDir, String fixture) throws IOException { + Files.writeString(dataDir.resolve("state.json"), Fixtures.read(fixture), StandardCharsets.UTF_8); + 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"); + registry.add("mediagarrd.client.password", () -> ""); + } + + static void assertPairingLoaded(ClientStateService state) { + assertEquals("http://192.168.1.20:38471", state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + assertNull(state.getLastPickupAt()); + assertEquals(Optional.of(new StoredPairing("golden-token-one", "c0ffee00-0000-4000-8000-000000000001", "Golden Laptop")), + state.pairingFor("http://192.168.1.20:38471")); + } + + @SpringBootTest + static class MissingInterval { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + register(registry, dataDir, "disk/state-no-interval.json"); + } + + @Test + void stateWithoutPickupIntervalStillLoadsItsPairings() { + assertPairingLoaded(state); + } + } + + @SpringBootTest + static class NullInterval { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + register(registry, dataDir, "disk/state-null-interval.json"); + } + + @Test + void stateWithNullPickupIntervalStillLoadsItsPairings() { + assertPairingLoaded(state); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java new file mode 100644 index 0000000..fbf1e9b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/StateFilesGoldenTest.java @@ -0,0 +1,91 @@ +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.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import wellatleastitried.mediagarrdclient.golden.Fixtures; + +@SpringBootTest +class StateFilesGoldenTest { + + @TempDir + static Path dataDir; + + @Autowired + ClientStateService state; + + @Autowired + PasswordService passwords; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) throws IOException { + Files.writeString(dataDir.resolve("state.json"), Fixtures.read("disk/state.json"), StandardCharsets.UTF_8); + Files.writeString(dataDir.resolve("password.json"), Fixtures.read("disk/password.json"), StandardCharsets.UTF_8); + 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"); + registry.add("mediagarrd.client.password", () -> ""); + } + + @Test + void stateWrittenInTodaysFormatStillLoadsWithItsPairings() { + assertEquals("http://192.168.1.20:38471", state.getActiveServer()); + assertEquals(Duration.ofSeconds(5400), state.getPickupInterval()); + assertEquals(Instant.parse("2026-11-20T03:15:00Z"), state.getLastPickupAt()); + assertEquals(List.of("http://192.168.1.20:38471", "https://backup.example.net:38471"), state.getKnownServers()); + assertEquals(Optional.of("golden-token-one"), state.tokenFor("http://192.168.1.20:38471")); + assertEquals(Optional.of(new StoredPairing("golden-token-one", "c0ffee00-0000-4000-8000-000000000001", "Golden Laptop")), + state.pairingFor("http://192.168.1.20:38471")); + assertEquals(Optional.of(new StoredPairing("golden-token-two", "c0ffee00-0000-4000-8000-000000000002", null)), + state.pairingFor("https://backup.example.net:38471")); + } + + @Test + void savingWritesTheSameShapeAsToday() throws Exception { + state.setPickupInterval(Duration.ofSeconds(5400)); + + String written = Files.readString(dataDir.resolve("state.json")); + JSONAssert.assertEquals(Fixtures.read("disk/state.json"), written, JSONCompareMode.STRICT); + assertEquals(keys(Fixtures.read("disk/state.json")), keys(written)); + } + + private static List keys(String json) { + List keys = new ArrayList<>(); + Matcher matcher = Pattern.compile("\"([^\"]+)\"\\s*:").matcher(json); + while (matcher.find()) { + keys.add(matcher.group(1)); + } + return keys; + } + + @Test + void aStoredPasswordStillLoadsAndVerifies() { + assertTrue(passwords.isConfigured()); + assertFalse(passwords.isFromEnvironment()); + assertTrue(passwords.matches("golden password")); + assertFalse(passwords.matches("another password")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java index 4310a64..af76343 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/UpdateCheckServiceTest.java @@ -19,11 +19,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; -import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.MediaGarrdProperties; import wellatleastitried.mediagarrdclient.dto.CheckState; import wellatleastitried.mediagarrdclient.dto.VersionStatusDto; @@ -33,7 +36,7 @@ class UpdateCheckServiceTest { private final List requests = new ArrayList<>(); private final List userAgents = new ArrayList<>(); - private final Configuration properties = new Configuration(); + private final MediaGarrdProperties properties = new MediaGarrdProperties(); private HttpServer server; private int status = 200; private String rateLimitRemaining; @@ -119,36 +122,16 @@ void reportsAnUpdateWhenTheLatestReleaseIsNewer() { 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"); + @ParameterizedTest + @CsvSource({"0.1.0,v0.1.0,0.1.0", "0.2.0,v0.1.0,0.1.0", "0.2.0,v0.2.0-rc.1,0.2.0-rc.1"}) + void reportsUpToDateWhenTheLatestReleaseIsTheSameOrOlder(String current, String tag, String latest) { + response = release(tag); + UpdateCheckService service = service(current); 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(); - + assertEquals(latest, service.status().latestVersion()); assertFalse(service.status().updateAvailable()); } @@ -268,9 +251,10 @@ void reportsAnErrorWithoutCallingGithubWhenTheCurrentVersionIsUnknown() { assertTrue(requests.isEmpty()); } - @Test - void buildsTheReleaseUrlWhenGithubOmitsIt() { - response = "{\"tag_name\": \"v0.3.0\"}"; + @ParameterizedTest + @ValueSource(strings = {", \"html_url\": \"javascript:alert(1)\"", ", \"html_url\": \"https://github.com.evil.example/x\"", ""}) + void replacesAReleaseUrlThatIsNotOnGithub(String htmlUrl) { + response = "{\"tag_name\": \"v0.3.0\"" + htmlUrl + "}"; UpdateCheckService service = service("0.1.0"); service.check(); diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java index 6cb5e16..85f64e2 100644 --- a/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/VersionServiceTest.java @@ -11,11 +11,8 @@ 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; @@ -32,23 +29,7 @@ class VersionServiceTest { 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 MutableClock clock = new MutableClock(NOW); private final UpdateCheckService updateCheckService = mock(UpdateCheckService.class); private final ServerApiService serverApiService = mock(ServerApiService.class); private final VersionService service = new VersionService(updateCheckService, serverApiService, clock); @@ -96,16 +77,16 @@ void refetchesAtMostHourlyAndAtOnceAfterAnInvalidation() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofMinutes(59))); + clock.set(NOW.plus(Duration.ofMinutes(59))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofHours(1))); + clock.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))); + clock.set(clock.instant().plus(Duration.ofMinutes(6))); assertTrue(service.invalidate(false)); assertTrue(service.needsRefresh()); } @@ -117,14 +98,14 @@ void aServerThatHasNotCheckedYetIsAskedAgainAfterThirtySeconds() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofSeconds(29))); + clock.set(NOW.plus(Duration.ofSeconds(29))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofSeconds(30))); + clock.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))); + clock.set(NOW.plus(Duration.ofMinutes(10))); assertFalse(service.needsRefresh()); } @@ -135,9 +116,9 @@ void aServerThatReportedAnErrorIsAskedAgainAfterFiveMinutes() { service.select(URL); service.refresh(); - now.set(NOW.plus(Duration.ofMinutes(4))); + clock.set(NOW.plus(Duration.ofMinutes(4))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofMinutes(5))); + clock.set(NOW.plus(Duration.ofMinutes(5))); assertTrue(service.needsRefresh()); assertTrue(service.invalidate(false)); } @@ -196,9 +177,9 @@ void reportsTheServerAsUnavailableWhenItCannotBeReachedAndRetriesSooner() { assertEquals(CLIENT, result.client()); assertEquals(CheckState.UNAVAILABLE, result.server().checkState()); assertFalse(result.server().updateAvailable()); - now.set(NOW.plus(Duration.ofMinutes(9))); + clock.set(NOW.plus(Duration.ofMinutes(9))); assertFalse(service.needsRefresh()); - now.set(NOW.plus(Duration.ofMinutes(10))); + clock.set(NOW.plus(Duration.ofMinutes(10))); assertTrue(service.needsRefresh()); } diff --git a/src/test/js/api.test.mjs b/src/test/js/api.test.mjs new file mode 100644 index 0000000..3ad3d2a --- /dev/null +++ b/src/test/js/api.test.mjs @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { api, errorMessage, onLoginRequired, onPairingRequired, retryAfterSeconds, toApiError } from '../../main/resources/static/js/api.js'; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; + onLoginRequired(() => {}); + onPairingRequired(() => {}); +}); + +function respond(status, body, headers = {}) { + globalThis.fetch = async () => new Response(typeof body === 'string' ? body : JSON.stringify(body), { + status, + headers: new Headers(headers), + }); +} + +test('the error contract maps to its message and Spring default bodies prefer the detail message, then the reason phrase', () => { + assert.equal(errorMessage({ error: 'No active MediaGarrd server selected' }, 'x'), 'No active MediaGarrd server selected'); + const spring = { timestamp: 't', status: 400, error: 'Bad Request', path: '/x' }; + assert.equal(errorMessage({ ...spring, message: 'Name is required' }, 'x'), 'Name is required'); + assert.equal(errorMessage({ ...spring, message: '' }, 'x'), 'Bad Request'); + assert.equal(errorMessage(spring, 'x'), 'Bad Request'); +}); + +test('a missing, empty or non-object body falls back to the generic message', () => { + assert.equal(errorMessage({}, 'GET /x failed (500)'), 'GET /x failed (500)'); + assert.equal(errorMessage(null, 'fb'), 'fb'); + assert.equal(errorMessage('text', 'fb'), 'fb'); + assert.equal(errorMessage({ error: 42, message: ' ' }, 'fb'), 'fb'); +}); + +test('Retry-After accepts seconds and HTTP dates and rejects the rest', () => { + assert.equal(retryAfterSeconds('30'), 30); + assert.equal(retryAfterSeconds(' 7 '), 7); + assert.equal(retryAfterSeconds('0'), 0); + const now = Date.parse('2026-01-10T12:00:00Z'); + assert.equal(retryAfterSeconds('Sat, 10 Jan 2026 12:01:00 GMT', now), 60); + assert.equal(retryAfterSeconds('Sat, 10 Jan 2026 11:00:00 GMT', now), 0); + assert.equal(retryAfterSeconds('soon'), null); + assert.equal(retryAfterSeconds(''), null); + assert.equal(retryAfterSeconds(null), null); + assert.equal(retryAfterSeconds(undefined), null); +}); + +test('toApiError carries status, pairing flag and retry delay', () => { + const error = toApiError({ + method: 'POST', url: '/api/auth/login', status: 429, + data: { error: 'Too many login attempts, try again in 12 seconds' }, retryAfter: '12', + }); + assert.equal(error.message, 'Too many login attempts, try again in 12 seconds'); + assert.equal(error.status, 429); + assert.equal(error.retryAfter, 12); + assert.equal(error.pairing, undefined); + assert.equal(toApiError({ method: 'GET', url: '/x', status: 502, data: { error: 'm', pairing: 'required' } }).pairing, 'required'); + assert.equal(toApiError({ method: 'GET', url: '/x', status: 500, data: {} }).message, 'The client answered with an error (500).'); + assert.equal(toApiError({ method: 'POST', url: '/x', status: 504, data: {} }).message, 'The client or a proxy in front of it did not respond in time.'); + assert.equal(toApiError({ method: 'POST', url: '/x', status: 502, data: {} }).message, 'The client or a proxy in front of it did not respond in time.'); + assert.equal(toApiError({ status: 504, data: { error: 'Backup timed out' } }).message, 'Backup timed out'); +}); + +test('a 401 with login required fires the login hook once and still throws', async () => { + let fired = 0; + onLoginRequired(() => { fired++; }); + respond(401, { login: 'required', error: 'Sign in' }); + await assert.rejects(api.dashboard(), (error) => error.status === 401 && error.message === 'Sign in'); + assert.equal(fired, 1); +}); + +test('a 401 without the login marker does not fire the login hook', async () => { + let fired = 0; + onLoginRequired(() => { fired++; }); + respond(401, { error: 'Incorrect password' }); + await assert.rejects(api.login('x'), /Incorrect password/); + assert.equal(fired, 0); +}); + +test('a 502 pairing required fires the pairing hook', async () => { + let fired = 0; + onPairingRequired(() => { fired++; }); + respond(502, { error: 'Pair first', pairing: 'required' }); + await assert.rejects(api.listBackups(), /Pair first/); + assert.equal(fired, 1); +}); + +test('a non-JSON error body still produces a useful error with the Retry-After value', async () => { + respond(503, 'bad gateway', { 'Retry-After': '9' }); + await assert.rejects(api.status(), (error) => error.status === 503 && error.retryAfter === 9 && error.message === 'The client answered with an error (503).'); +}); + +test('successful empty and JSON responses are parsed', async () => { + respond(200, ''); + assert.equal(await api.logout(), null); + respond(200, { authenticated: true }); + assert.deepEqual(await api.authStatus(), { authenticated: true }); +}); + +test('requests send the CSRF header and JSON bodies', async () => { + let seen; + globalThis.fetch = async (url, init) => { + seen = { url, init }; + return new Response('{}', { status: 200 }); + }; + await api.pair('123456'); + assert.equal(seen.url, '/api/client/pairing'); + assert.equal(seen.init.method, 'POST'); + assert.equal(seen.init.headers['X-MediaGarrd-Request'], '1'); + assert.equal(seen.init.body, JSON.stringify({ pin: '123456' })); + await api.pickupById('a/b c'); + assert.equal(seen.url, '/api/client/pickup/a%2Fb%20c'); +}); diff --git a/src/test/js/auth-model.test.mjs b/src/test/js/auth-model.test.mjs new file mode 100644 index 0000000..dd94c74 --- /dev/null +++ b/src/test/js/auth-model.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { authScreen, passwordProblem } from '../../main/resources/static/js/auth-model.js'; + +test('the auth screen follows the auth status', () => { + const cases = [ + [null, 'loading'], + [undefined, 'loading'], + [{ passwordSet: true, authenticated: true }, 'none'], + [{ passwordSet: true, authenticated: false }, 'login'], + [{ passwordSet: false, authenticated: false }, 'set-password'], + ]; + for (const [status, screen] of cases) { + assert.equal(authScreen(status), screen); + } +}); + +test('a new password needs eight characters and a matching repeat', () => { + assert.match(passwordProblem('short', 'short'), /at least 8/); + assert.match(passwordProblem('long enough', 'different'), /do not match/); + assert.equal(passwordProblem('long enough', 'long enough'), null); +}); + +test('the lockout message counts seconds and disappears at zero', async () => { + const { lockoutMessage } = await import('../../main/resources/static/js/auth-model.js'); + assert.equal(lockoutMessage(1), 'Too many login attempts. Try again in 1 second.'); + assert.equal(lockoutMessage(30), 'Too many login attempts. Try again in 30 seconds.'); + assert.equal(lockoutMessage(0), null); +}); diff --git a/src/test/js/busy.test.mjs b/src/test/js/busy.test.mjs new file mode 100644 index 0000000..09e816e --- /dev/null +++ b/src/test/js/busy.test.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { withBusy } from '../../main/resources/static/js/busy.js'; + +const savedDocument = globalThis.document; +afterEach(() => { + if (savedDocument === undefined) delete globalThis.document; + else globalThis.document = savedDocument; +}); + +function button(focused) { + const element = { disabled: false, focused: 0, focus() { this.focused++; } }; + globalThis.document = { activeElement: focused ? element : null }; + return element; +} + +test('the button is disabled while the task runs and restored afterwards', async () => { + const element = button(false); + let during; + const result = await withBusy(element, async () => { during = element.disabled; return 7; }); + assert.equal(during, true); + assert.equal(element.disabled, false); + assert.equal(result, 7); +}); + +test('focus returns to a button that had it, and only then', async () => { + const focused = button(true); + await withBusy(focused, async () => {}); + assert.equal(focused.focused, 1); + const other = button(false); + await withBusy(other, async () => {}); + assert.equal(other.focused, 0); +}); + +test('a second activation while busy is ignored', async () => { + const element = button(false); + let runs = 0; + let release; + const first = withBusy(element, () => new Promise((resolve) => { runs++; release = resolve; })); + assert.equal(await withBusy(element, async () => { runs++; }), undefined); + release(); + await first; + assert.equal(runs, 1); +}); + +test('the button is restored when the task throws', async () => { + const element = button(true); + await assert.rejects(withBusy(element, async () => { throw new Error('boom'); }), /boom/); + assert.equal(element.disabled, false); +}); diff --git a/src/test/js/dashboard-model.test.mjs b/src/test/js/dashboard-model.test.mjs index 501ae08..cfaf3c8 100644 --- a/src/test/js/dashboard-model.test.mjs +++ b/src/test/js/dashboard-model.test.mjs @@ -141,13 +141,6 @@ test('a run finishing reloads the backups, however it was learned', () => { 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); @@ -200,3 +193,23 @@ test('a connecting link forgets the run state and a first answer reloads the bac const up = reduce(connecting, 'link', { state: 'DEGRADED' }); assert.equal(changes(connecting, up, 'link').refreshBackups, true); }); + +test('a snapshot carries the pairing state and defaults to paired when it is missing', () => { + assert.equal(loaded({ pairing: 'REQUIRED' }).pairing, 'REQUIRED'); + assert.equal(loaded().pairing, 'PAIRED'); + assert.equal(loaded({ activeServer: null, pairing: 'NONE' }).pairing, 'NONE'); +}); + +test('a pairing event changes the pairing state', () => { + const state = reduce(loaded({ pairing: 'PAIRED' }), 'pairing', { state: 'REJECTED' }); + assert.equal(state.pairing, 'REJECTED'); + assert.equal(reduce(state, 'pairing', { state: 'PAIRED' }).pairing, 'PAIRED'); +}); + +test('archives are not loaded for a server that is not paired and load once pairing succeeds', () => { + assert.equal(canLoadBackups(loaded({ pairing: 'REQUIRED' })), false); + assert.equal(canLoadBackups(loaded({ pairing: 'REJECTED' })), false); + const rejected = loaded({ pairing: 'REJECTED' }); + const result = applyEvent(rejected, 'pairing', { state: 'PAIRED' }); + assert.equal(result.effects.refreshBackups, true); +}); diff --git a/src/test/js/events.test.mjs b/src/test/js/events.test.mjs new file mode 100644 index 0000000..96c2221 --- /dev/null +++ b/src/test/js/events.test.mjs @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { EVENT_NAMES, initEvents } from '../../main/resources/static/js/events.js'; + +const JAVA_ROOT = fileURLToPath(new URL('../../main/java', import.meta.url)); + +function javaFiles(dir) { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + return statSync(path).isDirectory() ? javaFiles(path) : path.endsWith('.java') ? [path] : []; + }); +} + +function publishedByJava() { + const names = new Set(); + const sources = javaFiles(JAVA_ROOT).map((file) => readFileSync(file, 'utf8')); + for (const source of sources) { + for (const match of source.matchAll(/\b(?:publish|publishRaw)\(\s*"([a-z][a-z-]*)"/g)) names.add(match[1]); + for (const match of source.matchAll(/new ClientEvent\(\s*"([a-z][a-z-]*)"/g)) names.add(match[1]); + } + const stream = sources.find((source) => source.includes('FORWARDED_EVENTS = Set.of(')); + const forwarded = /FORWARDED_EVENTS = Set\.of\(([^)]*)\)/.exec(stream)[1].match(/"[a-z-]+"/g).map((quoted) => quoted.slice(1, -1)); + forwarded.filter((name) => name !== 'config-changed').forEach((name) => names.add(name)); + names.delete('close'); + return names; +} + +test('EVENT_NAMES covers every event the Java client publishes, and nothing else', () => { + const published = publishedByJava(); + assert.ok(published.size >= 10, `expected to find the published events, found ${[...published]}`); + assert.deepEqual([...EVENT_NAMES].sort(), [...published].sort()); +}); + +class FakeSource { + static CLOSED = 2; + static instances = []; + constructor(url) { + this.url = url; + this.readyState = 1; + this.listeners = {}; + this.closed = false; + FakeSource.instances.push(this); + } + addEventListener(name, handler) { (this.listeners[name] ||= []).push(handler); } + close() { this.closed = true; } + emit(name, event = {}) { (this.listeners[name] || []).forEach((handler) => handler(event)); } +} + +const saved = {}; +beforeEach(() => { + FakeSource.instances = []; + for (const key of ['EventSource', 'document', 'window', 'setInterval', 'setTimeout']) saved[key] = globalThis[key]; + globalThis.EventSource = FakeSource; + globalThis.document = { hidden: false, addEventListener() {} }; + globalThis.window = { addEventListener() {} }; + globalThis.setInterval = () => 0; + globalThis.setTimeout = () => 0; +}); +afterEach(() => { + for (const key of Object.keys(saved)) { + if (saved[key] === undefined) delete globalThis[key]; + else globalThis[key] = saved[key]; + } +}); + +test('every declared event name is subscribed, including pairing', () => { + initEvents({ onEvent() {}, onConnection() {} }); + const [source] = FakeSource.instances; + assert.deepEqual(EVENT_NAMES.filter((name) => !source.listeners[name]), []); + assert.ok(source.listeners.pairing); +}); + +test('a pairing event reaches the handler as parsed JSON and pings are swallowed', () => { + const seen = []; + initEvents({ onEvent: (name, payload) => seen.push([name, payload]), onConnection() {} }); + const [source] = FakeSource.instances; + source.emit('pairing', { data: '{"state":"REJECTED"}' }); + source.emit('ping', { data: '{}' }); + source.emit('link', { data: 'not json' }); + assert.deepEqual(seen, [['pairing', { state: 'REJECTED' }]]); +}); + +test('a stream refused before it ever opened checks the session', async () => { + let checks = 0; + const connection = []; + initEvents({ onEvent() {}, onConnection: (reachable) => connection.push(reachable), checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 1); + assert.equal(source.closed, true); + assert.deepEqual(connection, [false]); +}); + +test('a stream that dropped after opening does not check the session', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 0); +}); + +test('a refused reconnect after a stream that was open checks the session', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = 0; + source.emit('error'); + assert.equal(checks, 0); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 1); +}); + +test('a reconnect that opened again does not check the session when it later drops', () => { + let checks = 0; + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; } }); + const [source] = FakeSource.instances; + source.emit('open'); + source.readyState = 0; + source.emit('error'); + source.readyState = 1; + source.emit('open'); + source.readyState = FakeSource.CLOSED; + source.emit('error'); + assert.equal(checks, 0); +}); + +test('a failing session check is swallowed and the stream is still reopened', async () => { + let checks = 0; + let reopens = 0; + const unhandled = []; + const onUnhandled = (reason) => unhandled.push(reason); + process.on('unhandledRejection', onUnhandled); + globalThis.setTimeout = () => { reopens++; return 1; }; + try { + initEvents({ onEvent() {}, onConnection() {}, checkSession: async () => { checks++; throw new Error('down'); } }); + const [source] = FakeSource.instances; + source.readyState = FakeSource.CLOSED; + source.emit('error'); + await new Promise((resolve) => setImmediate(resolve)); + } finally { + process.off('unhandledRejection', onUnhandled); + } + assert.equal(checks, 1); + assert.equal(reopens, 1); + assert.deepEqual(unhandled, []); +}); diff --git a/src/test/js/format.test.mjs b/src/test/js/format.test.mjs new file mode 100644 index 0000000..0ad5676 --- /dev/null +++ b/src/test/js/format.test.mjs @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import { afterEach, test } from 'node:test'; +import { bytes, formatInterval, intervalProblem, percent, pickupProblem, relativeTime, seconds, toDuration, toHours } from '../../main/resources/static/js/format.js'; + +const realNow = Date.now; +afterEach(() => { Date.now = realNow; }); + +test('seconds reads ISO durations, plain numbers and garbage', () => { + assert.equal(seconds('PT6H'), 21600); + assert.equal(seconds('PT1H30M'), 5400); + assert.equal(seconds('PT45S'), 45); + assert.equal(seconds('pt0.5H'), 1800); + assert.equal(seconds(90), 90); + assert.equal(seconds('nonsense'), 0); + assert.equal(seconds(null), 0); + assert.equal(seconds(undefined), 0); +}); + +test('toDuration uses whole minutes when it can and seconds otherwise', () => { + assert.equal(toDuration(5), 'PT5M'); + assert.equal(toDuration(90), 'PT90M'); + assert.equal(toDuration(0.5), 'PT30S'); + assert.equal(toDuration(0.25 * 60), 'PT15M'); +}); + +test('toHours rounds to four decimals and survives a round trip', () => { + assert.equal(toHours('PT6H'), 6); + assert.equal(toHours('PT15M'), 0.25); + assert.equal(toHours('PT20M'), 0.3333); + assert.equal(seconds(toDuration(toHours('PT20M') * 60)), 1200); + assert.equal(seconds(toDuration(toHours('PT5M') * 60)), 300); +}); + +test('formatInterval is compact and shows a dash for zero or unknown', () => { + assert.equal(formatInterval('PT6H'), '6h'); + assert.equal(formatInterval('PT90M'), '1h 30m'); + assert.equal(formatInterval('PT45S'), '45s'); + assert.equal(formatInterval('PT0S'), '—'); + assert.equal(formatInterval(null), '—'); +}); + +test('bytes picks a unit and caps at TB', () => { + assert.equal(bytes(0), '0 B'); + assert.equal(bytes(undefined), '0 B'); + assert.equal(bytes(512), '512 B'); + assert.equal(bytes(1536), '1.5 KB'); + assert.equal(bytes(5 * 1024 ** 2), '5.0 MB'); + assert.equal(bytes(3 * 1024 ** 4), '3.0 TB'); + assert.equal(bytes(2048 * 1024 ** 4), '2048.0 TB'); +}); + +test('relativeTime buckets and clamps the future', () => { + Date.now = () => Date.parse('2026-01-10T12:00:00Z'); + assert.equal(relativeTime('2026-01-10T11:59:30Z'), '30s ago'); + assert.equal(relativeTime('2026-01-10T11:55:00Z'), '5m ago'); + assert.equal(relativeTime('2026-01-10T09:00:00Z'), '3h ago'); + assert.equal(relativeTime('2026-01-08T12:00:00Z'), '2d ago'); + assert.equal(relativeTime('2026-01-11T12:00:00Z'), '0s ago'); + assert.equal(relativeTime('not a date'), '—'); + assert.equal(relativeTime(undefined), '—'); +}); + +test('percent is clamped and safe for an unknown total', () => { + assert.equal(percent(50, 200), 25); + assert.equal(percent(300, 200), 100); + assert.equal(percent(-5, 200), 0); + assert.equal(percent(5, 0), 0); + assert.equal(percent(5, undefined), 0); +}); + +test('intervalProblem accepts 15 minutes to 365 days and names the bounds otherwise', () => { + const message = 'Backup interval must be between 15 minutes and 365 days'; + assert.equal(intervalProblem(0.25), null); + assert.equal(intervalProblem(12), null); + assert.equal(intervalProblem(8760), null); + for (const hours of [0, -1, 0.24, 8760.01, 1e9, NaN, Infinity]) assert.equal(intervalProblem(hours), message); +}); + +test('pickupProblem accepts 1 minute to 365 days and rejects the rest', () => { + assert.equal(pickupProblem(1), null); + assert.equal(pickupProblem(525600), null); + assert.ok(pickupProblem(525601)); + assert.ok(pickupProblem(0.5)); + assert.ok(pickupProblem(0)); + assert.ok(pickupProblem(NaN)); + assert.ok(pickupProblem(Infinity)); +}); diff --git a/src/test/js/notify.test.mjs b/src/test/js/notify.test.mjs new file mode 100644 index 0000000..596f3b4 --- /dev/null +++ b/src/test/js/notify.test.mjs @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { createNotifier } from '../../main/resources/static/js/notify.js'; + +function banner() { + const attributes = {}; + return { + textContent: '', + className: 'banner', + attributes, + scrolled: 0, + setAttribute(name, value) { attributes[name] = value; }, + scrollIntoView() { this.scrolled++; }, + }; +} + +test('errors are assertive and scrolled into view', () => { + const element = banner(); + createNotifier(element).error(new Error('Nope')); + assert.equal(element.textContent, 'Nope'); + assert.equal(element.className, 'banner visible error'); + assert.equal(element.attributes['aria-live'], 'assertive'); + assert.equal(element.scrolled, 1); +}); + +test('success is polite and does not scroll; warnings scroll', () => { + const element = banner(); + const notify = createNotifier(element); + notify.ok('Saved'); + assert.equal(element.className, 'banner visible ok'); + assert.equal(element.attributes['aria-live'], 'polite'); + assert.equal(element.scrolled, 0); + notify.warn('Careful'); + assert.equal(element.className, 'banner visible warn'); + assert.equal(element.scrolled, 1); + notify.clear(); + assert.equal(element.className, 'banner'); +}); + +test('a non-Error rejection is shown as text', () => { + const element = banner(); + createNotifier(element).error('plain'); + assert.equal(element.textContent, 'plain'); +}); diff --git a/src/test/js/pairing-model.test.mjs b/src/test/js/pairing-model.test.mjs new file mode 100644 index 0000000..0a5f410 --- /dev/null +++ b/src/test/js/pairing-model.test.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { emptyState, reduce } from '../../main/resources/static/js/dashboard-model.js'; +import { codeView, credentialProblem, pairingNote, pairingPanel } from '../../main/resources/static/js/pairing-model.js'; + +const loaded = (overrides = {}) => reduce(emptyState(), 'snapshot', { + activeServer: 'https://garrd.example.com', + knownServers: ['https://garrd.example.com'], + link: 'DEGRADED', + running: null, + health: null, + versions: null, + pairing: 'PAIRED', + ...overrides, +}); + +test('the pairing panel is hidden until a reachable server is selected', () => { + assert.equal(pairingPanel(emptyState()), 'hidden'); + assert.equal(pairingPanel(loaded({ activeServer: null, pairing: 'NONE' })), 'hidden'); + assert.equal(pairingPanel(loaded({ link: 'DOWN' })), 'hidden'); + assert.equal(pairingPanel(loaded({ link: 'CONNECTING', pairing: 'REQUIRED' })), 'hidden'); +}); + +test('an unpaired or rejected server asks for pairing and a paired one offers codes and unpairing', () => { + assert.equal(pairingPanel(loaded({ pairing: 'REQUIRED' })), 'pair'); + assert.equal(pairingPanel(loaded({ pairing: 'REJECTED' })), 'pair'); + assert.equal(pairingPanel(loaded({ pairing: 'PAIRED', link: 'LIVE' })), 'manage'); +}); + +test('a rejected token is explained differently from a missing one', () => { + const rejected = pairingNote(loaded({ pairing: 'REJECTED' })); + assert.match(rejected, /no longer accepts/); + assert.match(rejected, /^The server no longer accepts this client\. Enter a pairing code from a client that is still paired\./); + assert.match(rejected, /Pairing PIN.*only when no client is paired.*MEDIAGARRD_OPEN_PAIRING/); + assert.match(pairingNote(loaded({ pairing: 'REQUIRED' })), /Pairing PIN/); +}); + +test('an empty credential is refused before it is sent', () => { + assert.ok(credentialProblem(' ')); + assert.ok(credentialProblem(undefined)); + assert.equal(credentialProblem(' 123456 '), null); +}); + +test('a pairing code counts down and then reads as expired', () => { + const code = { code: 'ABCDE-FGHJK', expiresAt: '2026-11-19T12:10:00Z' }; + const start = Date.parse('2026-11-19T12:00:00Z'); + assert.deepEqual(codeView(code, start), { text: 'ABCDE-FGHJK', expires: 'Expires in 10:00' }); + assert.equal(codeView(code, start + 541_000).expires, 'Expires in 0:59'); + assert.equal(codeView(code, start + 600_000).expires, 'Expired'); + assert.equal(codeView(null, start), null); +}); diff --git a/src/test/js/view-model.test.mjs b/src/test/js/view-model.test.mjs index 3a3f8ba..83b4949 100644 --- a/src/test/js/view-model.test.mjs +++ b/src/test/js/view-model.test.mjs @@ -1,7 +1,7 @@ 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'; +import { classifyVersion, configUnavailableMessage, linkView, listingError, planKnown, versionsView } from '../../main/resources/static/js/view-model.js'; const loaded = (overrides = {}) => reduce(emptyState(), 'snapshot', { activeServer: 'http://a:38471', @@ -32,7 +32,7 @@ test('a live server shows its details and the host in the badge', () => { 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.badge.kind, 'degraded'); assert.equal(view.showDetails, true); assert.equal(view.degraded, true); }); @@ -140,3 +140,39 @@ test('a server that has not answered yet is connecting, not unreachable', () => assert.equal(view.showDetails, false); assert.equal(view.message, 'Connecting to http://a:38471…'); }); + +test('a reachable server that is not paired says pairing is required', () => { + const view = linkView(loaded({ pairing: 'REQUIRED', link: 'DEGRADED' })); + assert.deepEqual(view.badge, { kind: 'down', label: 'Pairing required' }); + assert.equal(view.showDetails, false); + assert.match(view.message, /not paired with http:\/\/a:38471/); +}); + +test('a rejected token is reported as such', () => { + const view = linkView(loaded({ pairing: 'REJECTED', link: 'DEGRADED' })); + assert.match(view.message, /rejected this client's token/); +}); + +test('an unreachable server is reported as unreachable before pairing is mentioned', () => { + const view = linkView(loaded({ pairing: 'REQUIRED', link: 'DOWN' })); + assert.equal(view.badge.label, 'Unreachable'); +}); + +test('a listing error only suggests connecting when no server is connected', () => { + const error = new Error('The server rejected this client\'s token, pair it again'); + assert.equal(listingError(error, true), 'The server rejected this client\'s token, pair it again.'); + assert.equal(listingError(error, false), 'The server rejected this client\'s token, pair it again. Connect to a server to view archives.'); +}); + +test('a message that already ends in punctuation gets no second full stop', () => { + const error = new Error('The client or a proxy in front of it did not respond in time.'); + assert.equal(listingError(error, true), 'The client or a proxy in front of it did not respond in time.'); + assert.equal(listingError(error, false), 'The client or a proxy in front of it did not respond in time. Connect to a server to view archives.'); + assert.match(configUnavailableMessage(error), /in time\. Connect to a MediaGarrd server/); +}); + +test('the server configuration message tells an unpaired client to pair and otherwise keeps the reason', () => { + const unpaired = Object.assign(new Error('This client is not paired with the server, pair it first'), { pairing: 'required' }); + assert.equal(configUnavailableMessage(unpaired), 'Pair this client with the server on the Dashboard to manage its configuration.'); + assert.match(configUnavailableMessage(new Error('No active MediaGarrd server selected')), /^No active MediaGarrd server selected\. Connect to a MediaGarrd server/); +}); diff --git a/src/test/js/webhook.test.mjs b/src/test/js/webhook.test.mjs new file mode 100644 index 0000000..96ee940 --- /dev/null +++ b/src/test/js/webhook.test.mjs @@ -0,0 +1,238 @@ +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, test } from 'node:test'; +import { readFileSync } from 'node:fs'; +import { describeStatus, describeTest, initWebhook } from '../../main/resources/static/js/webhook.js'; + +const realFetch = globalThis.fetch; +const savedDocument = globalThis.document; +let calls; +let replies; + +beforeEach(() => { + calls = []; + replies = []; + globalThis.document = { activeElement: null }; + globalThis.fetch = async (url, init) => { + calls.push({ url, method: init.method, headers: init.headers, body: init.body }); + const reply = replies.shift() || { status: 200, body: {} }; + return new Response(JSON.stringify(reply.body), { status: reply.status, headers: new Headers(reply.headers || {}) }); + }; +}); + +afterEach(() => { + globalThis.fetch = realFetch; + if (savedDocument === undefined) delete globalThis.document; + else globalThis.document = savedDocument; +}); + +function button() { + const listeners = {}; + return { disabled: false, listeners, addEventListener(name, fn) { listeners[name] = fn; } }; +} + +function setup() { + const url = { value: '' }; + const label = { textContent: '' }; + const parts = { '[data-webhook-status]': label, '[data-webhook-test]': button(), '[data-webhook-clear]': button(), 'button[type="submit"]': button() }; + const form = { + elements: { url }, + listeners: {}, + addEventListener(name, fn) { this.listeners[name] = fn; }, + querySelector: (selector) => parts[selector], + }; + const messages = []; + const notify = { + ok: (message) => messages.push(['ok', message]), + error: (error) => messages.push(['error', error.message]), + clear: () => messages.push(['clear']), + }; + const view = initWebhook(form, notify); + return { form, url, label, parts, messages, view }; +} + +const submit = (form) => form.listeners.submit({ preventDefault() {} }); +const settled = (messages) => messages.filter((entry) => entry[0] !== 'clear'); + +test('a configured webhook shows only its target and an unset one says so', () => { + assert.equal(describeStatus({ configured: true, target: 'https://discord.com' }), 'Configured: https://discord.com'); + assert.equal(describeStatus({ configured: false, target: null }), 'Not configured'); + assert.equal(describeStatus(null), 'Not configured'); +}); + +test('a test result names the reason when it was not delivered', () => { + assert.deepEqual(describeTest({ delivered: true, status: 200, error: null }), { ok: true, message: 'Test message delivered' }); + assert.deepEqual(describeTest({ delivered: false, status: 404, error: 'Webhook answered 404' }), + { ok: false, message: 'Test message was not delivered: Webhook answered 404' }); + assert.equal(describeTest({ delivered: false }).ok, false); +}); + +test('loading shows the target and never fills the input', async () => { + const { url, label, view } = setup(); + replies.push({ status: 200, body: { configured: true, target: 'https://hooks.slack.com' } }); + await view.load(); + assert.equal(label.textContent, 'Configured: https://hooks.slack.com'); + assert.equal(url.value, ''); + assert.equal(calls[0].method, 'GET'); + assert.equal(calls[0].url, '/api/client/notifications/webhook'); +}); + +test('a failed load says it is unavailable instead of breaking the page', async () => { + const { label, view } = setup(); + replies.push({ status: 404, body: { error: 'Not Found' } }); + await view.load(); + assert.equal(label.textContent, 'Unavailable: Not Found'); +}); + +test('saving sends the typed URL with the CSRF header, clears the input and shows the target', async () => { + const { form, url, label, messages } = setup(); + url.value = ' https://discord.com/api/webhooks/1/SECRET '; + replies.push({ status: 200, body: { configured: true, target: 'https://discord.com' } }); + await submit(form); + assert.equal(calls[0].method, 'PUT'); + assert.equal(calls[0].url, '/api/client/notifications/webhook'); + assert.equal(calls[0].headers['X-MediaGarrd-Request'], '1'); + assert.deepEqual(JSON.parse(calls[0].body), { url: 'https://discord.com/api/webhooks/1/SECRET' }); + assert.equal(url.value, ''); + assert.equal(label.textContent, 'Configured: https://discord.com'); + assert.deepEqual(settled(messages), [['ok', 'Webhook saved']]); +}); + +test('saving an empty field makes no request and points to Clear', async () => { + const { form, messages } = setup(); + await submit(form); + assert.equal(calls.length, 0); + assert.equal(settled(messages)[0][0], 'error'); +}); + +test('a rejected URL shows the server message and keeps the typed text', async () => { + const { form, url, messages } = setup(); + url.value = 'ftp://example.com'; + replies.push({ status: 400, body: { error: 'Webhook URL must use http or https' } }); + await submit(form); + assert.equal(url.value, 'ftp://example.com'); + assert.deepEqual(settled(messages), [['error', 'Webhook URL must use http or https']]); +}); + +test('clearing sends an empty URL', async () => { + const { parts, label, messages } = setup(); + replies.push({ status: 200, body: { configured: false, target: null } }); + await parts['[data-webhook-clear]'].listeners.click(); + assert.deepEqual(JSON.parse(calls[0].body), { url: '' }); + assert.equal(label.textContent, 'Not configured'); + assert.deepEqual(settled(messages), [['ok', 'Webhook cleared']]); +}); + +test('Send test reports a delivered message', async () => { + const { parts, messages } = setup(); + replies.push({ status: 200, body: { delivered: true, status: 200, error: null } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.equal(calls.length, 1); + assert.equal(calls[0].method, 'POST'); + assert.equal(calls[0].url, '/api/client/notifications/webhook/test'); + assert.equal(calls[0].headers['X-MediaGarrd-Request'], '1'); + assert.deepEqual(settled(messages), [['ok', 'Test message delivered']]); +}); + +test('Send test saves a typed URL first and reports a failed delivery', async () => { + const { parts, url, messages } = setup(); + url.value = 'https://example.com/hook'; + replies.push({ status: 200, body: { configured: true, target: 'https://example.com' } }); + replies.push({ status: 200, body: { delivered: false, status: 404, error: 'Webhook answered 404' } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.deepEqual(calls.map((call) => call.method), ['PUT', 'POST']); + assert.deepEqual(settled(messages), [['error', 'Test message was not delivered: Webhook answered 404']]); +}); + +test('a test inside the cooldown shows the wait from the server', async () => { + const { parts, messages } = setup(); + replies.push({ status: 429, body: { error: 'Wait 7 seconds before sending another test' }, headers: { 'Retry-After': '7' } }); + await parts['[data-webhook-test]'].listeners.click(); + assert.deepEqual(settled(messages), [['error', 'Wait 7 seconds before sending another test']]); +}); + +test('the buttons are busy while a request runs and restored after', async () => { + const { parts } = setup(); + const test = parts['[data-webhook-test]']; + let during; + globalThis.fetch = async () => { + during = test.disabled; + return new Response(JSON.stringify({ delivered: true }), { status: 200 }); + }; + await test.listeners.click(); + assert.equal(during, true); + assert.equal(test.disabled, false); +}); + +test('the other buttons are disabled while one action runs and a second action is ignored', async () => { + const { parts } = setup(); + const test = parts['[data-webhook-test]']; + const clear = parts['[data-webhook-clear]']; + let release; + globalThis.fetch = () => new Promise((resolve) => { release = () => resolve(new Response(JSON.stringify({ delivered: true }), { status: 200 })); }); + const running = test.listeners.click(); + assert.equal(clear.disabled, true); + assert.equal(parts['button[type="submit"]'].disabled, true); + const ignored = await clear.listeners.click(); + assert.equal(ignored, undefined); + release(); + await running; + assert.equal(clear.disabled, false); + assert.equal(parts['button[type="submit"]'].disabled, false); +}); + +test('a save that finishes after a server switch does not change the new server label', async () => { + const { form, url, label, view } = setup(); + url.value = 'https://example.com/hook'; + let release; + globalThis.fetch = () => new Promise((resolve) => { release = () => resolve(new Response(JSON.stringify({ configured: true, target: 'https://example.com' }), { status: 200 })); }); + const pending = submit(form); + view.reset(); + release(); + await pending; + assert.equal(label.textContent, 'Checking…'); +}); + +test('switching servers drops the displayed state', () => { + const { url, label, view } = setup(); + url.value = 'https://x.example/y'; + view.reset(); + assert.equal(url.value, ''); + assert.equal(label.textContent, 'Checking…'); +}); + +test('the page has the webhook panel with a never-prefilled url input', () => { + const html = readFileSync(new URL('../../main/resources/static/index.html', import.meta.url), 'utf8'); + assert.match(html, /id="webhookForm"/); + assert.match(html, /id="webhookUrl" name="url" type="url" autocomplete="off"/); + assert.match(html, /data-webhook-test/); + assert.match(html, /data-webhook-clear/); + assert.doesNotMatch(html, /id="webhookUrl"[^>]*value=/); +}); + +test('a note followed by a field group gets the same gap as between field groups', () => { + const css = readFileSync(new URL('../../main/resources/static/css/mediagarrd.css', import.meta.url), 'utf8'); + assert.match(css, /\.note \+ \.field-group \{ margin-top: 0\.75rem; \}/); + const html = readFileSync(new URL('../../main/resources/static/index.html', import.meta.url), 'utf8'); + assert.match(html, /<\/p>\s*
\s*