diff --git a/CHANGELOG b/CHANGELOG index f3c0b04..a483054 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,44 +1,55 @@ # CHANGELOG +## 11-12-26 +- A run rejected before it starts (such as no services configured) publishes no run events +- A scheduled check with nothing to back up now waits one full interval instead of retrying every 30 seconds, and adding or editing a service makes the schedule due again right away +- `GET /api/v1/events` also sends `backups-changed` (backup deleted, backup location changed) and `config-changed` (schedule, settings, or services changed), each as `{"at":""}` +- `GET /api/v1/health` and `GET /api/v1/backups` are logged at DEBUG, so polling no longer fills the log + +## 11-11-26 +- `GET /api/v1/events` is a live Server-Sent Events stream that needs no setup session: `state` on connect, `run-started` and `run-finished` (`COMPLETED`, `PARTIAL`, or `FAILED`) the moment a run begins and ends, and a `ping` every 20 seconds +- At most 16 listeners are served (more get `503`), a slow or dead listener is dropped without slowing a backup, and each stream ends cleanly after 4.5 minutes so clients reconnect without errors in the log +- Fixed a failed delete of a run's temporary directory leaving the server stuck on "running" and rejecting configuration changes until restart +- The server knows its version (`0.1.0`) and checks GitHub for the latest `MediaGarrd/Server` release shortly after starting and then daily +- `GET /api/v1/version` (no setup session needed) reports the current and latest version, whether an update is available, the release link, when the last check ran, and its state (`OK`, `NO_RELEASES`, `ERROR`, or `NOT_CHECKED`) +- A failed check (offline, rate limited, no release yet) is logged once, shown as a state, and never affects backups +- `MEDIAGARRD_UPDATE_REPOSITORY`, `MEDIAGARRD_GITHUB_API_URL`, and `MEDIAGARRD_UPDATE_CHECK_INTERVAL` change the repository, API address, and check interval (at least `PT1H`, or the server refuses to start) +- Scheduled tasks run on two threads (`spring.task.scheduling.pool.size: 2`), so a slow GitHub check cannot delay backups + ## 11-05-26 -- Every backup archive now includes a consistent snapshot of the server's own database (settings, services, and backup records), stored at its absolute host path so the future recovery tool and `bsdtar -xpf -C /` restore it in place -- The host path is found by inspecting the server's own container, a run is reported as partial with the error logged if it cannot be found or the snapshot fails, and a corrupt or missing database is never replaced by an empty one -- All database operations now wait while the snapshot is taken, so nothing is written to the database mid-copy -- The database snapshot appears as `_mediagarrd-server` in each run's service results and in the API's service names -- A service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to the snapshot in the archive +- Every archive includes a consistent snapshot of the server's own database (settings, services, backup records) at its absolute host path, so the future recovery tool and `bsdtar -xpf -C /` restore it in place +- The host path is found by inspecting the server's own container. If that or the snapshot fails, the run is partial with the error logged, and a corrupt or missing database is never replaced by an empty one +- Database operations wait while the snapshot is taken, so nothing is written mid-copy +- The snapshot appears as `_mediagarrd-server` in service results and service names, and a service copy of the database file or its `-journal`, `-wal`, and `-shm` files no longer replaces or sits next to it - Documented how to restore the database from an archive ## 10-26-26 -- Fixed logic issue with migration versioning -- Added Structurizr diagrams to visualize workflow -- Added Lombok for simpler model classes -- Services are now stored in the database and managed from the `/config` web page or `/api/v1/services`, any service can be backed up +- Services are stored in the database and managed from `/config` or `/api/v1/services`, and any service can be backed up - Backup location can be changed at runtime from `/config` or `PUT /api/v1/config` -- Replaced the per-service runners with a single runner that copies each service's paths through a cached, read-only helper container via the Docker socket -- Added integration test and issue label workflows +- Backup interval and retention count are stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting +- Configuration changes are rejected while a backup is running, so a run never sees its services change +- One runner now copies each service's paths through a cached, read-only helper container via the Docker socket, replacing the per-service runners - Added first-time web setup reachable from the network, unlocked with a single-use PIN printed in the server logs and disabled once setup is finished -- `docker-compose.example.yml` now works without `install.sh` -- Backup interval and retention count are now stored in the database, retention is settable through `PUT /api/v1/config`, and `GET /api/v1/config` returns every setting -- Configuration changes are rejected while a backup is running so a run never sees its services change underneath it -- Added a pull request check that requires every linked issue to be approved -- Backup archives are laid out by absolute host path with no per-service folder, so they can be restored with `bsdtar -xpf -C /` -- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy no longer leaves partial files in the archive +- `docker-compose.example.yml` works without `install.sh` +- Archives are laid out by absolute host path with no per-service folder, so `bsdtar -xpf -C /` restores them +- Archives keep permissions, owners, modification times, symbolic links, and empty directories, and a path that fails to copy leaves no partial files - Fixed special files (pipes, devices) being archived as empty regular files -- Fixed backup checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly -- Every API endpoint now returns errors as `{"error": "..."}` with a matching status code -- The database schema is verified once and then re-checked with a single query per call, rebuilding or upgrading the database whenever it is deleted, altered, or replaced, and moving a corrupt database aside +- Fixed checksums loading the whole archive into memory and dropping leading zeros, and archive sizes over 2 GB being recorded incorrectly +- Every API endpoint returns errors as `{"error": "..."}` with a matching status code +- The database schema is verified once and then re-checked with one query per call, rebuilding or upgrading the database when it is deleted, altered, or replaced, and moving a corrupt one aside +- Fixed migration versioning +- Added Structurizr diagrams, Lombok for model classes, integration test and issue label workflows, and a pull request check that requires every linked issue to be approved ## 9-23-26 -- Add database for keeping records of backups -- Add thorough testing of database functionality -- Add issue templates -- Removed auto-routing to appdata/ within archive to retain actual paths of configs +- Added a database for backup records, with thorough tests +- Added issue templates +- Removed auto-routing to `appdata/` within archives so configs keep their actual paths ## 9-16-26 -- Adding more detailed logging for service runners -- Renaming QBittorrent's "graveyard" directory to "saved-torrents" to make it less ambiguous +- More detailed logging for service runners +- Renamed QBittorrent's "graveyard" directory to "saved-torrents" ## 9-6-26 -- Abstracting services to make adding new ones easier -- Adding new tests -- Project renaming +- Abstracted services to make adding new ones easier +- Added new tests +- Renamed the project diff --git a/README.md b/README.md index f963bc2..15ecfeb 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ # Server -This is the official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +The official server for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). It backs up the configuration of the services on its host into a single zip archive on a schedule, and the [MediaGarrd Client](https://github.com/MediaGarrd/Client) manages it and downloads the archives to another machine. + +Full documentation, including configuration, archives and restoring, is on the [MediaGarrd website](https://mediagarrd.github.io/MediaGarrd/). + +## Docs +- [settings.md](./docs/settings.md): every environment variable and its default. +- [API.md](./docs/API.md): every HTTP endpoint and what it returns. +- [database.md](./docs/database.md): recovering the server's database from a backup. ## Requirements -- A Linux host running Docker with Compose v2 (`docker compose ...`) -- The host paths of the services you want to back up +- A Linux host running Docker with Compose v2 ## Installation ```bash @@ -14,74 +20,19 @@ cp docker-compose.example.yml docker-compose.yml docker compose up --build -d ``` -The defaults in `docker-compose.yml` work as-is. To change them before the first start: -- **Port:** change both `SERVER_PORT` and the `ports` mapping (default `38471`). -- **Where archives are stored on the host:** change the left side of the `./data/server/backups` volume. -- **Where the database is stored on the host:** change the left side of the `./data/server/db` volume. This holds every setting and service, so keep it on persistent storage. - -## First-time setup -Until setup is finished, the server prints a single-use setup PIN to its logs: +Then get the single-use setup PIN from the logs: ```bash docker logs mediagarrd-server 2>&1 | grep "Setup PIN" ``` -From any device on the network, open `http://:38471/config` and enter the PIN. A new PIN is logged each time one is used, after 5 wrong attempts, and on every restart. - -On the setup page: -1. **Backup Settings:** the backup location (a path *inside* the container that must be on a mounted volume, default `/var/lib/mediagarrd/backups`), the hours between backups, and how many backups to keep. -2. **Services:** add each service with a name and the absolute **host** paths to back up. Any service can be backed up. A path can be a directory (everything inside it is included) or a single file (only that file is included). -3. **Finish Setup:** available once at least one service exists. The setup page is then disabled for good. - -## Configuration after setup -Every setting is stored in the database and survives restarts and container rebuilds. After setup, change them through the API or the MediaGarrd Client: - -| Setting | Endpoint | -|---------|----------| -| Read all settings | `GET /api/v1/config` | -| Backup location and/or backups to keep | `PUT /api/v1/config` with `{"backupLocation": "/path", "retentionCount": 10}` | -| Time between backups (ISO-8601) | `PUT /api/v1/schedule` with `{"backupInterval": "PT12H"}` | -| List / add services | `GET` / `POST /api/v1/services` with `{"name": "radarr", "paths": ["/srv/radarr/config"]}` | -| Update / remove a service | `PUT` / `DELETE /api/v1/services/{name}` | - -Configuration changes are rejected with `409 Conflict` while a backup is running. A lower retention count takes effect on the next backup run. - -`MEDIAGARRD_BACKUP_INTERVAL` and `MEDIAGARRD_RETENTION_COUNT` in `docker-compose.yml` only set the initial values. Once a value has been saved through setup or the API, the stored value is used. - -The database is checked on startup and whenever its schema changes underneath the server. If it is deleted, has a table dropped, or is replaced by an older copy, it is rebuilt or upgraded automatically. A corrupt database is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty one, after which settings and services must be configured again (restart the server to get a new setup PIN). +Open `http://:38471/config`, enter the PIN, add the services to back up, and finish setup. ## Updating ```bash git pull docker compose up --build -d ``` -Settings, services, and archives live in the mounted `./data/server` volumes and are kept. - -## How backups work -On every backup run the server creates (but never starts) a small helper container per service with its paths mounted read-only, and streams them into the backup archive through the Docker API. The helper container is reused until the service's paths change. - -### Archive layout -Every entry in a backup zip sits at its absolute host path without the leading `/`, with no per-service folder. A service backing up `/etc/nginx/sites-available/default` and `/srv/radarr/config` produces: -``` -etc/nginx/sites-available/default -srv/radarr/config/ -srv/radarr/config/config.xml -... -``` -Each entry keeps its permissions, owner (uid/gid), and modification time. Symbolic links are stored as links, empty directories are kept, and hard links are stored as regular copies. Named pipes, sockets, and device files are skipped. If two services back up the same path it appears once. If a path fails to copy, none of it is included and the run is reported as partial. - -Every archive also contains a consistent snapshot of the server's own database (settings, services, and backup records) at the database file's absolute host path, for example `home/you/MediaGarrd/data/server/db/mediagarrd.db` when `./data/server/db` is mounted at `/var/lib/mediagarrd/db`. The server finds that host path by inspecting its own container, and no other database operation runs while the snapshot is taken. If the path cannot be resolved or the snapshot fails, the archive is still created, the run is reported as partial, and the error is listed under `_mediagarrd-server` (which also shows up in each run's service list). The snapshot never contains the record of its own run. On Docker Desktop (macOS and Windows) the host path reported by Docker is a path inside its VM, so the snapshot's location in the archive will not match your real host path. If a service also backs up the database directory, the snapshot replaces that service's copy of the database file, and its `-journal`, `-wal`, and `-shm` files are left out of the archive. - -### Restoring -Because the layout mirrors the filesystem, restoring is a single extraction onto `/`. Use `bsdtar` (libarchive, the `libarchive-tools` package on Debian/Ubuntu), which restores contents, permissions, owners, modification times, and symbolic links: -```bash -sudo bsdtar -xpf .zip -C / -``` -Extract into an empty directory with `-C ` to inspect a backup first. - -To restore the server's database, stop the server first (`docker compose stop`), extract the snapshot into an empty directory, copy it over `mediagarrd.db` in the mounted database directory (`./data/server/db`), then start the server again. Do not extract it over a running server's database. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. - -Info-ZIP `unzip -o .zip -d /` restores contents, permissions, and symbolic links, but UnZip 6.00 (the version most distributions ship) does not restore owners, so files end up owned by whoever ran it. Tools that ignore Unix metadata, such as Python's `zipfile` or most GUI archive managers, restore only the file contents. -> **Security:** the server needs `/var/run/docker.sock`, which gives it root-equivalent access to the host. During setup the configuration API requires the PIN session, but once setup is finished the API is unauthenticated, so do not expose the server port to untrusted networks. +> **Security:** the server mounts `/var/run/docker.sock`, which gives it root-equivalent access to the host, and its API is unauthenticated after setup. Do not expose its port to untrusted networks. ## License [MIT](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index 49a78a2..b749201 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" + extra["httpclient5.version"] = "5.4.4" extra["httpcore5.version"] = "5.3.4" @@ -31,6 +33,10 @@ java { } } +springBoot { + buildInfo() +} + tasks.test { useJUnitPlatform() } diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..f6743eb --- /dev/null +++ b/docs/API.md @@ -0,0 +1,41 @@ +# Server API + +All endpoints are under `/api/v1`. Errors are returned as `{"error": "..."}` with a matching status code. + +## Status +| Endpoint | Returns | +|---|---| +| `GET /health` | The server's health, whether a backup is running, the number of backups to keep, and the time between backups. | +| `GET /version` | The running version and the result of the daily check for a newer GitHub release. | +| `GET /events` | A Server-Sent Events stream that reports when backup runs start and finish and when archives or configuration change. | + +## Setup +| Endpoint | Returns | +|---|---| +| `GET /setup` | Whether first-time setup is finished and whether the caller holds a setup session. | +| `POST /setup/session` | An empty `204` and a setup session cookie when the posted PIN is correct. | +| `POST /setup/complete` | An empty `204` once setup is finished, after which the setup page is disabled. | + +The setup page itself is served at `GET /config` until setup is finished. + +## Configuration +| Endpoint | Returns | +|---|---| +| `GET /config` | The backup location, the number of backups to keep, and the time between backups. | +| `PUT /config` | The updated configuration after changing the backup location and/or the number of backups to keep. | +| `PUT /schedule` | The server status after changing the time between backups. | +| `GET /services` | Every configured service with its host paths. | +| `POST /services` | The added service, with `201`. | +| `PUT /services/{name}` | The updated service. | +| `DELETE /services/{name}` | An empty `204` once the service is removed. | + +## Backups +| Endpoint | Returns | +|---|---| +| `GET /backups` | Every archive with its id, file name, size, and creation time. | +| `GET /backups/latest` | The newest archive's details. | +| `GET /backups/{id}` | One archive's details. | +| `GET /backups/latest/download` | The newest archive as a zip file. | +| `GET /backups/{id}/download` | One archive as a zip file. | +| `DELETE /backups/{id}` | An empty `204` once the archive is deleted. | +| `POST /backups/run` | The run id, start and end time, services that ran, and the new archive, once the backup finishes. | diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 0000000..f2bf1ed --- /dev/null +++ b/docs/database.md @@ -0,0 +1,43 @@ +# Recovering the database + +Every backup archive contains a consistent copy of the server's own database: its settings, services, and backup records. The copy is taken while no other database operation runs, so it is never half written. It does not contain the record of the run that created it. + +## Where the copy is in the archive +The copy sits at the database file's absolute host path, without the leading `/`. With the example `docker-compose.yml`, which mounts `./data/server/db` at `/var/lib/mediagarrd/db`, that is something like: +``` +home/you/Server/data/server/db/mediagarrd.db +``` +To find it in an archive: +```bash +bsdtar -tf .zip | grep 'mediagarrd\.db$' +``` +If the copy could not be taken, the archive has no database entry and the run was reported as partial with the error listed under `_mediagarrd-server`. + +On Docker Desktop (macOS and Windows) the path is one inside Docker's VM, so it will not match your real host path. The file name is still `mediagarrd.db`. + +## Restoring it +Never restore over the database of a running server. + +1. Stop the server: + ```bash + docker compose stop + ``` +2. Extract the copy into an empty directory: + ```bash + mkdir restore + bsdtar -xpf .zip -C restore '' + ``` +3. Copy it over the current database in the mounted database directory (`./data/server/db` with the example compose file): + ```bash + cp restore/ ./data/server/db/mediagarrd.db + rm -f ./data/server/db/mediagarrd.db-journal ./data/server/db/mediagarrd.db-wal ./data/server/db/mediagarrd.db-shm + ``` +4. Start the server again: + ```bash + docker compose start + ``` + +`bsdtar` is in the `libarchive-tools` package on Debian and Ubuntu. Extracting the whole archive with `-C /` also writes the database to its host path, which is only safe while the server is stopped. + +## If the database is damaged +The server checks its database on startup. A missing or outdated database is rebuilt or upgraded automatically. A corrupt one is moved aside to `mediagarrd.db.corrupt-` and replaced with an empty database, so the server starts again with no settings or services. Restore a copy from the newest archive as above to get them back, or restart the server and use its new setup PIN to configure it again. diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..a1a3df3 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,21 @@ +# Settings + +Set these in `environment` in `docker-compose.yml`. Durations use ISO-8601, for example `PT12H`. + +| Variable | Default | What it does | +|---|---|---| +| `SERVER_PORT` | `8080` (`38471` in the example compose file) | The port of the API and setup page. Change the `ports` mapping to match. | +| `MEDIAGARRD_BACKUP_INTERVAL` | `PT12H` | The time between scheduled backups. Only the initial value: once it is saved through setup, the API, or the client, the stored value is used. | +| `MEDIAGARRD_RETENTION_COUNT` | `10` | How many backups to keep. Only the initial value, like the interval. | +| `MEDIAGARRD_BACKUP_ROOT` | `/var/lib/mediagarrd/backups` | Where archives are stored, inside the container. Only the initial value. It must be on a mounted volume. | +| `MEDIAGARRD_DATABASE_PATH` | `/var/lib/mediagarrd/db/mediagarrd.db` | The database file, inside the container. It must be on a mounted volume. | +| `MEDIAGARRD_HELPER_IMAGE` | `busybox:stable` | The image used for the helper containers that read each service's files. | +| `MEDIAGARRD_UPDATE_REPOSITORY` | `MediaGarrd/Server` | 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`. | + +To change where data is kept on the host, change the left side of the volumes in `docker-compose.yml`: +- `./data/server/backups`: the archives. +- `./data/server/db`: the database, which holds every setting and service. Keep it on persistent storage. + +The server also needs `/var/run/docker.sock` mounted to run its helper containers. diff --git a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java index 26a2705..b50e931 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/MediaGarrdProperties.java @@ -17,4 +17,7 @@ public class MediaGarrdProperties { private int retentionCount = 10; private String databasePath = "/var/lib/mediagarrd/db/mediagarrd.db"; private String helperImage = "busybox:stable"; + private String updateRepository = "MediaGarrd/Server"; + private String githubApiBaseUrl = "https://api.github.com"; + private Duration updateCheckInterval = Duration.ofHours(24); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java index 1ca9085..0158ca2 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/BackupController.java @@ -32,6 +32,7 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; @RestController @RequestMapping("/api/v1") @@ -41,15 +42,17 @@ public class BackupController { private final BackupArchiveService archiveService; private final BackupOrchestratorService orchestratorService; + private final RunStatusBroadcaster broadcaster; - public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService) { + public BackupController(BackupArchiveService archiveService, BackupOrchestratorService orchestratorService, RunStatusBroadcaster broadcaster) { this.archiveService = archiveService; this.orchestratorService = orchestratorService; + this.broadcaster = broadcaster; } @GetMapping("/health") public ServerStatusDto health() { - LOGGER.info("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); + LOGGER.debug("GET /api/v1/health, running={}, interval={}", orchestratorService.isRunning(), orchestratorService.getInterval()); return status(orchestratorService.getInterval()); } @@ -58,14 +61,15 @@ public ServerStatusDto updateSchedule(@RequestBody ScheduleUpdateRequest request LOGGER.info("PUT /api/v1/schedule, requestedInterval={}", request.backupInterval()); Duration updated = orchestratorService.updateInterval(request.backupInterval()); LOGGER.info("Schedule updated: newInterval={}", updated); + broadcaster.publishConfigChanged(); return status(updated); } @GetMapping("/backups") public List listBackups() { - LOGGER.info("GET /api/v1/backups"); + LOGGER.debug("GET /api/v1/backups"); List backups = archiveService.listArchives().stream().map(this::toDto).toList(); - LOGGER.info("Returning {} backup(s)", backups.size()); + LOGGER.debug("Returning {} backup(s)", backups.size()); return backups; } @@ -111,6 +115,7 @@ public ResponseEntity deleteBackup(@PathVariable String id) { return ResponseEntity.notFound().build(); } LOGGER.info("Backup deleted: {}", id); + broadcaster.publishBackupsChanged(); return ResponseEntity.noContent().build(); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java index d1ca6d1..420e896 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/ConfigController.java @@ -25,6 +25,7 @@ import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; import wellatleastitried.mediagarrdServer.service.DatabaseService; import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; @RestController @RequestMapping("/api/v1") @@ -36,17 +37,20 @@ public class ConfigController { private final BackupOrchestratorService orchestrator; private final DatabaseService db; private final DockerService docker; + private final RunStatusBroadcaster broadcaster; public ConfigController( BackupArchiveService archiveService, BackupOrchestratorService orchestrator, DatabaseService db, - DockerService docker + DockerService docker, + RunStatusBroadcaster broadcaster ) { this.archiveService = archiveService; this.orchestrator = orchestrator; this.db = db; this.docker = docker; + this.broadcaster = broadcaster; } @GetMapping("/config") @@ -60,6 +64,10 @@ public ServerConfigDto updateConfig(@RequestBody ConfigUpdateRequest request) { LOGGER.info("PUT /api/v1/config, backupLocation={}, retentionCount={}", request.backupLocation(), request.retentionCount()); return orchestrator.whileIdle(() -> { archiveService.updateSettings(request.backupLocation(), request.retentionCount()); + if (request.backupLocation() != null) { + broadcaster.publishBackupsChanged(); + } + broadcaster.publishConfigChanged(); return currentConfig(); }); } @@ -79,6 +87,8 @@ public ResponseEntity addService(@RequestBody ServiceDefinition request) { return error(HttpStatus.CONFLICT, "Service already exists: " + service.name()); } db.addService(service); + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); return ResponseEntity.status(HttpStatus.CREATED).body(service); }); } @@ -100,6 +110,8 @@ public ResponseEntity updateService(@PathVariable String name, @RequestBody S if (!service.name().equals(currentName)) { docker.removeContainers(currentName); } + orchestrator.servicesChanged(); + broadcaster.publishConfigChanged(); return ResponseEntity.ok(service); }); } @@ -114,6 +126,7 @@ public ResponseEntity removeService(@PathVariable String name) { } db.removeService(existing.get().name()); docker.removeContainers(existing.get().name()); + broadcaster.publishConfigChanged(); return ResponseEntity.noContent().build(); }); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java new file mode 100644 index 0000000..c4f2f86 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/RunEventsController.java @@ -0,0 +1,49 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpStatus; +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 jakarta.servlet.http.HttpServletResponse; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster.SubscriberLimitException; + +@RestController +@RequestMapping("/api/v1") +public class RunEventsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunEventsController.class); + + private final RunStatusBroadcaster broadcaster; + + public RunEventsController(RunStatusBroadcaster broadcaster) { + this.broadcaster = broadcaster; + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public ResponseEntity events() { + try { + return ResponseEntity.ok() + .cacheControl(CacheControl.noCache()) + .header("X-Accel-Buffering", "no") + .body(broadcaster.subscribe()); + } catch (SubscriberLimitException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build(); + } + } + + @ExceptionHandler({AsyncRequestTimeoutException.class, AsyncRequestNotUsableException.class}) + public void streamEnded(Exception e, HttpServletResponse response) { + LOGGER.debug("Event stream ended: {}", e.toString()); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java new file mode 100644 index 0000000..99bb197 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/api/VersionController.java @@ -0,0 +1,24 @@ +package wellatleastitried.mediagarrdServer.api; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@RestController +@RequestMapping("/api/v1") +public class VersionController { + + private final UpdateCheckService updateCheckService; + + public VersionController(UpdateCheckService updateCheckService) { + this.updateCheckService = updateCheckService; + } + + @GetMapping("/version") + public VersionStatusDto version() { + return updateCheckService.status(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java new file mode 100644 index 0000000..96f73ce --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/CheckState.java @@ -0,0 +1,8 @@ +package wellatleastitried.mediagarrdServer.dto; + +public enum CheckState { + NOT_CHECKED, + OK, + NO_RELEASES, + ERROR +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java new file mode 100644 index 0000000..18fb393 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/dto/VersionStatusDto.java @@ -0,0 +1,13 @@ +package wellatleastitried.mediagarrdServer.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/mediagarrdServer/service/BackupOrchestratorService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java index 2729377..4130464 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorService.java @@ -52,7 +52,9 @@ public class BackupOrchestratorService { private final BackupScheduleService scheduleService; private final DatabaseSnapshotService snapshotService; private final DatabaseService db; + private final RunStatusBroadcaster broadcaster; private final AtomicBoolean running = new AtomicBoolean(false); + private final Object transitionLock = new Object(); private final ReentrantReadWriteLock configLock = new ReentrantReadWriteLock(); private final ExecutorService runnerExecutor = createRunnerExecutor(); @@ -61,13 +63,15 @@ public BackupOrchestratorService( BackupArchiveService archiveService, BackupScheduleService scheduleService, DatabaseSnapshotService snapshotService, - DatabaseService db + DatabaseService db, + RunStatusBroadcaster broadcaster ) { this.runner = runner; this.archiveService = archiveService; this.scheduleService = scheduleService; this.snapshotService = snapshotService; this.db = db; + this.broadcaster = broadcaster; } private static ExecutorService createRunnerExecutor() { @@ -98,104 +102,148 @@ public void scheduledRun() { } LOGGER.info("Scheduled backup triggered, next run at {}", scheduleService.getNextRun()); try { - runBackup(); + runBackup(true); + } catch (RunRejectedException ex) { + LOGGER.warn("Scheduled backup skipped: {}", ex.getMessage()); } catch (RuntimeException ex) { LOGGER.error("Scheduled backup run failed", ex); } } public BackupRunResult runBackup() { - if (!running.compareAndSet(false, true)) { - LOGGER.warn("runBackup() called while backup already in progress, rejecting"); - throw new RunRejectedException("A backup run is already in progress"); - } + return runBackup(false); + } - configLock.readLock().lock(); - Path runDirectory = null; - try { - List services = db.fetchServices(); - if (services.isEmpty()) { - LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); - throw new RunRejectedException("No services are configured for backup"); + BackupRunResult runBackup(boolean scheduled) { + Instant startedAt = Instant.now(); + String finalStatus = FAILED; + boolean started = false; + synchronized (transitionLock) { + if (!running.compareAndSet(false, true)) { + LOGGER.warn("runBackup() called while backup already in progress, rejecting"); + throw new RunRejectedException("A backup run is already in progress"); } - - scheduleService.markRunStarted(); - runDirectory = archiveService.createRunDirectory(); - final Path runDir = runDirectory; - Instant startedAt = Instant.now(); - - LOGGER.info("Backup run started: runDir={}, services={}", - runDir, services.stream().map(ServiceDefinition::name).toList()); - - List> futures = services.stream() - .map(service -> CompletableFuture - .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) - .exceptionally(t -> { - Throwable cause = unwrap(t); - LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); - return failedResult(service.name(), cause); - })) - .toList(); - - List serviceRunResults = futures.stream() - .map(CompletableFuture::join) - .toList(); - - List incomplete = serviceRunResults.stream() - .filter(r -> !COMPLETED.equals(r.status())) - .toList(); - int succeeded = services.size() - incomplete.size(); - LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); - incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); - - String errorMessage = incomplete.stream() - .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) - .collect(Collectors.joining("\n")); - - if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { - String runId = "failed-" + UUID.randomUUID(); - serviceRunResults.forEach(r -> r.setId(runId)); - db.addNewBackupRecord(new BackupRunResult( - runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); - LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); - throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + } + try { + configLock.readLock().lock(); + Path runDirectory = null; + try { + List services = db.fetchServices(); + if (services.isEmpty()) { + LOGGER.warn("No services are configured, aborting backup run before creating a run directory"); + if (scheduled) { + scheduleService.deferNextRun(); + } + throw new RunRejectedException("No services are configured for backup"); + } + started = true; + publishStarted(startedAt); + + scheduleService.markRunStarted(); + runDirectory = archiveService.createRunDirectory(); + final Path runDir = runDirectory; + + LOGGER.info("Backup run started: runDir={}, services={}", + runDir, services.stream().map(ServiceDefinition::name).toList()); + + List> futures = services.stream() + .map(service -> CompletableFuture + .supplyAsync(() -> runner.run(service, runDir), runnerExecutor) + .exceptionally(t -> { + Throwable cause = unwrap(t); + LOGGER.warn("Runner {} failed unexpectedly", service.name(), cause); + return failedResult(service.name(), cause); + })) + .toList(); + + List serviceRunResults = futures.stream() + .map(CompletableFuture::join) + .toList(); + + List incomplete = serviceRunResults.stream() + .filter(r -> !COMPLETED.equals(r.status())) + .toList(); + int succeeded = services.size() - incomplete.size(); + LOGGER.info("All runners finished: succeeded={}/{}", succeeded, services.size()); + incomplete.forEach(r -> LOGGER.warn("Runner did not complete (non-fatal): {} ({})", r.serviceName(), r.status())); + + String errorMessage = incomplete.stream() + .map(r -> r.serviceName() + ": " + Objects.requireNonNullElse(r.errorMessage(), "no details")) + .collect(Collectors.joining("\n")); + + if (succeeded == 0 && incomplete.stream().allMatch(r -> FAILED.equals(r.status()))) { + String runId = "failed-" + UUID.randomUUID(); + serviceRunResults.forEach(r -> r.setId(runId)); + db.addNewBackupRecord(new BackupRunResult( + runId, formatTime(startedAt), recordCurrentTime(), FAILED, serviceRunResults, null, errorMessage)); + LOGGER.error("Every service failed, no archive created (run {}):\n{}", runId, errorMessage); + throw new IllegalStateException("Every service failed, no archive created: " + errorMessage); + } + + BackupServiceResult snapshotResult = snapshotDatabase(runDir); + List recordedResults = new ArrayList<>(serviceRunResults); + recordedResults.add(snapshotResult); + boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status()); + if (snapshotFailed) { + LOGGER.warn("Database snapshot did not complete (non-fatal): {}", snapshotResult.errorMessage()); + String snapshotError = SNAPSHOT_NAME + ": " + Objects.requireNonNullElse(snapshotResult.errorMessage(), "no details"); + errorMessage = errorMessage.isEmpty() ? snapshotError : errorMessage + "\n" + snapshotError; + } + + BackupArchive archive = archiveService.createArchive(runDirectory); + recordedResults.forEach(r -> r.setId(archive.id())); + + long durationMs = Duration.between(startedAt, Instant.now()).toMillis(); + LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", + archive.fileName(), archive.sizeBytes(), durationMs, + recordedResults.stream().map(BackupServiceResult::serviceName).toList()); + + String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; + if (snapshotFailed && COMPLETED.equals(status)) { + status = PARTIAL; + } + + BackupRunResult backupRecord = new BackupRunResult( + archive.id(), formatTime(startedAt), recordCurrentTime(), status, + recordedResults, archive, errorMessage); + db.addNewBackupRecord(backupRecord); + finalStatus = status; + return backupRecord; + } finally { + try { + if (runDirectory != null) { + archiveService.removeRunDirectory(runDirectory); + LOGGER.debug("Run directory cleaned up: {}", runDirectory); + } + } catch (RuntimeException e) { + LOGGER.error("Failed to clean up run directory {}", runDirectory, e); + } finally { + configLock.readLock().unlock(); + } } - - BackupServiceResult snapshotResult = snapshotDatabase(runDir); - List recordedResults = new ArrayList<>(serviceRunResults); - recordedResults.add(snapshotResult); - boolean snapshotFailed = !COMPLETED.equals(snapshotResult.status()); - if (snapshotFailed) { - LOGGER.warn("Database snapshot did not complete (non-fatal): {}", snapshotResult.errorMessage()); - String snapshotError = SNAPSHOT_NAME + ": " + Objects.requireNonNullElse(snapshotResult.errorMessage(), "no details"); - errorMessage = errorMessage.isEmpty() ? snapshotError : errorMessage + "\n" + snapshotError; + } finally { + synchronized (transitionLock) { + running.set(false); + if (started) { + publishFinished(finalStatus, startedAt); + } } + } + } - BackupArchive archive = archiveService.createArchive(runDirectory); - recordedResults.forEach(r -> r.setId(archive.id())); - - long durationMs = Duration.between(startedAt, Instant.now()).toMillis(); - LOGGER.info("Backup run complete: archive={}, size={}B, duration={}ms, services={}", - archive.fileName(), archive.sizeBytes(), durationMs, - recordedResults.stream().map(BackupServiceResult::serviceName).toList()); - - String status = succeeded == services.size() ? COMPLETED : succeeded > 0 ? PARTIAL : FAILED; - if (snapshotFailed && COMPLETED.equals(status)) { - status = PARTIAL; - } + private void publishStarted(Instant startedAt) { + try { + broadcaster.publishStarted(startedAt); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-started event", e); + } + } - BackupRunResult backupRecord = new BackupRunResult( - archive.id(), formatTime(startedAt), recordCurrentTime(), status, - recordedResults, archive, errorMessage); - db.addNewBackupRecord(backupRecord); - return backupRecord; - } finally { - if (runDirectory != null) { - archiveService.removeRunDirectory(runDirectory); - LOGGER.debug("Run directory cleaned up: {}", runDirectory); - } - configLock.readLock().unlock(); - running.set(false); + private void publishFinished(String status, Instant startedAt) { + try { + broadcaster.publishFinished(status, startedAt, Instant.now()); + } catch (RuntimeException e) { + LOGGER.warn("Failed to publish run-finished event", e); } } @@ -235,6 +283,10 @@ public T whileIdle(Supplier configChange) { } } + public void servicesChanged() { + scheduleService.releaseDeferral(); + } + public boolean isRunning() { return running.get(); } diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java index ba01349..1b21d86 100644 --- a/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/BackupScheduleService.java @@ -6,6 +6,7 @@ import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; @@ -22,6 +23,7 @@ public class BackupScheduleService { private final DatabaseService db; private final AtomicReference currentInterval; private final AtomicReference nextRun; + private final AtomicBoolean deferred = new AtomicBoolean(); public BackupScheduleService(MediaGarrdProperties properties, DatabaseService db) { this.db = db; @@ -47,6 +49,7 @@ public Duration updateInterval(Duration interval) { currentInterval.set(safe); Instant next = Instant.now().plus(safe); nextRun.set(next); + deferred.set(false); LOGGER.info("Backup interval updated: newInterval={}, nextRunAt={}", safe, next); return safe; } @@ -60,9 +63,24 @@ public boolean dueNow() { public void markRunStarted() { Instant next = Instant.now().plus(currentInterval.get()); nextRun.set(next); + deferred.set(false); LOGGER.info("Backup run started: nextScheduledRun={}", next); } + public void deferNextRun() { + Instant next = Instant.now().plus(currentInterval.get()); + nextRun.set(next); + deferred.set(true); + LOGGER.info("Nothing to back up yet, next scheduled check at {}", next); + } + + public void releaseDeferral() { + if (deferred.compareAndSet(true, false)) { + nextRun.set(Instant.now()); + LOGGER.info("Services are configured, the next scheduled backup is due now"); + } + } + private static Optional parse(String stored) { try { return Optional.of(Duration.parse(stored)).filter(BackupScheduleService::isValid); diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java new file mode 100644 index 0000000..0a19f73 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcaster.java @@ -0,0 +1,228 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +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.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import jakarta.annotation.PreDestroy; + +@Service +public class RunStatusBroadcaster { + + private static final Logger LOGGER = LoggerFactory.getLogger(RunStatusBroadcaster.class); + + static final int MAX_SUBSCRIBERS = 16; + static final long EMITTER_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(6); + static final long ROLLOVER_MS = TimeUnit.SECONDS.toMillis(270); + static final long PING_INTERVAL_MS = TimeUnit.SECONDS.toMillis(20); + static final int QUEUE_CAPACITY = 8; + + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); + private static final Message CLOSE = new Message("close", ""); + + private final Object lock = new Object(); + private final List subscribers = new ArrayList<>(); + private final int maxSubscribers; + private final long emitterTimeoutMs; + private final long pingIntervalMs; + private final long rolloverMs; + private final ThreadFactory threadFactory; + private boolean running; + private boolean shutdown; + + public RunStatusBroadcaster() { + this(MAX_SUBSCRIBERS, EMITTER_TIMEOUT_MS, PING_INTERVAL_MS, ROLLOVER_MS, RunStatusBroadcaster::newWriterThread); + } + + RunStatusBroadcaster(int maxSubscribers, long emitterTimeoutMs, long pingIntervalMs, long rolloverMs, ThreadFactory threadFactory) { + this.maxSubscribers = maxSubscribers; + this.emitterTimeoutMs = emitterTimeoutMs; + this.pingIntervalMs = pingIntervalMs; + this.rolloverMs = rolloverMs; + this.threadFactory = threadFactory; + } + + private static Thread newWriterThread(Runnable runnable) { + Thread thread = new Thread(runnable, "run-events-writer-" + THREAD_COUNTER.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + + public SseEmitter subscribe() { + return subscribe(new SseEmitter(emitterTimeoutMs)); + } + + SseEmitter subscribe(SseEmitter emitter) { + Subscriber subscriber = new Subscriber(emitter); + synchronized (lock) { + if (shutdown || subscribers.size() >= maxSubscribers) { + throw new SubscriberLimitException("Too many event stream subscribers"); + } + subscriber.queue.offer(new Message("state", stateJson(running, Instant.now()))); + subscribers.add(subscriber); + } + emitter.onTimeout(subscriber::close); + emitter.onCompletion(subscriber::ended); + emitter.onError(error -> subscriber.ended()); + Thread writer = threadFactory.newThread(subscriber::writeLoop); + writer.start(); + return emitter; + } + + public void publishStarted(Instant startedAt) { + publish("run-started", Boolean.TRUE, "{\"running\":true,\"startedAt\":\"" + startedAt + "\"}"); + } + + public void publishFinished(String status, Instant startedAt, Instant finishedAt) { + publish("run-finished", Boolean.FALSE, "{\"running\":false,\"status\":\"" + status.toUpperCase(Locale.ROOT) + + "\",\"startedAt\":\"" + startedAt + "\",\"finishedAt\":\"" + finishedAt + "\"}"); + } + + public void publishBackupsChanged() { + publish("backups-changed", null, atJson()); + } + + public void publishConfigChanged() { + publish("config-changed", null, atJson()); + } + + private static String atJson() { + return "{\"at\":\"" + Instant.now() + "\"}"; + } + + private void publish(String name, Boolean nowRunning, String json) { + Message message = new Message(name, json); + synchronized (lock) { + if (nowRunning != null) { + running = nowRunning; + } + for (Subscriber subscriber : new ArrayList<>(subscribers)) { + if (!subscriber.queue.offer(message)) { + LOGGER.warn("Event stream subscriber is not keeping up, dropping it"); + subscribers.remove(subscriber); + subscriber.close(); + } + } + } + } + + int subscriberCount() { + synchronized (lock) { + return subscribers.size(); + } + } + + @PreDestroy + public void shutdown() { + List toClose; + synchronized (lock) { + shutdown = true; + toClose = new ArrayList<>(subscribers); + subscribers.clear(); + } + toClose.forEach(Subscriber::close); + } + + private static String stateJson(boolean running, Instant at) { + return "{\"running\":" + running + ",\"at\":\"" + at + "\"}"; + } + + private record Message(String name, String data) { + } + + public static class SubscriberLimitException extends RuntimeException { + public SubscriberLimitException(String message) { + super(message); + } + } + + private final class Subscriber { + + private final SseEmitter emitter; + private final BlockingQueue queue = new LinkedBlockingQueue<>(QUEUE_CAPACITY); + private final AtomicBoolean closed = new AtomicBoolean(); + private final AtomicBoolean ended = new AtomicBoolean(); + + Subscriber(SseEmitter emitter) { + this.emitter = emitter; + } + + void close() { + closed.set(true); + queue.offer(CLOSE); + } + + void ended() { + ended.set(true); + synchronized (lock) { + subscribers.remove(this); + } + close(); + } + + void writeLoop() { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(rolloverMs); + try { + while (!closed.get()) { + long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMs <= 0) { + break; + } + Message message = queue.poll(Math.min(pingIntervalMs, remainingMs), TimeUnit.MILLISECONDS); + if (message == null) { + if (System.nanoTime() - deadline >= 0) { + break; + } + message = new Message("ping", "{}"); + } + if (message == CLOSE || closed.get()) { + break; + } + emitter.send(SseEmitter.event().name(message.name()).data(message.data())); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (IOException | RuntimeException e) { + LOGGER.debug("Event stream write failed, dropping subscriber: {}", e.toString()); + closed.set(true); + synchronized (lock) { + subscribers.remove(this); + } + finish(e); + return; + } + synchronized (lock) { + subscribers.remove(this); + } + finish(null); + } + + private void finish(Exception error) { + if (ended.get()) { + return; + } + try { + if (error == null) { + emitter.complete(); + } else { + emitter.completeWithError(error); + } + } catch (RuntimeException e) { + LOGGER.debug("Completing the event stream failed: {}", e.toString()); + } + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java new file mode 100644 index 0000000..799880e --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/service/UpdateCheckService.java @@ -0,0 +1,171 @@ +package wellatleastitried.mediagarrdServer.service; + +import java.net.http.HttpClient; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; + +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.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.utilities.SemVer; + +@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; + + @Autowired + public UpdateCheckService(MediaGarrdProperties properties, ObjectProvider buildProperties) { + this(properties, versionOf(buildProperties), Clock.systemUTC()); + } + + UpdateCheckService(MediaGarrdProperties properties, String currentVersion, Clock clock) { + Duration interval = properties.getUpdateCheckInterval(); + if (interval == null || interval.compareTo(MIN_INTERVAL) < 0) { + throw new IllegalStateException("mediagarrd.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-Server/" + (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(); + } + + @Scheduled(initialDelayString = "PT5S", fixedDelayString = "${mediagarrd.update-check-interval:PT24H}") + public void check() { + VersionStatusDto previous = status.get(); + VersionStatusDto next = fetch(); + status.set(next); + logChange(previous, next); + } + + 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 void logChange(VersionStatusDto previous, VersionStatusDto next) { + boolean changed = previous.checkState() != next.checkState() + || !Objects.equals(previous.latestVersion(), next.latestVersion()) + || !Objects.equals(previous.message(), next.message()); + if (!changed) { + 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/mediagarrdServer/utilities/SemVer.java b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java new file mode 100644 index 0000000..1a10f86 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdServer/utilities/SemVer.java @@ -0,0 +1,78 @@ +package wellatleastitried.mediagarrdServer.utilities; + +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/resources/application.yml b/src/main/resources/application.yml index c0984fa..2ce92ec 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,9 +1,18 @@ server: port: ${SERVER_PORT:8080} +spring: + task: + scheduling: + pool: + size: 2 + mediagarrd: backup-interval: ${MEDIAGARRD_BACKUP_INTERVAL:PT12H} backup-root: ${MEDIAGARRD_BACKUP_ROOT:/var/lib/mediagarrd/backups} retention-count: ${MEDIAGARRD_RETENTION_COUNT:10} database-path: ${MEDIAGARRD_DATABASE_PATH:/var/lib/mediagarrd/db/mediagarrd.db} helper-image: ${MEDIAGARRD_HELPER_IMAGE:busybox:stable} + update-repository: ${MEDIAGARRD_UPDATE_REPOSITORY:MediaGarrd/Server} + github-api-base-url: ${MEDIAGARRD_GITHUB_API_URL:https://api.github.com} + update-check-interval: ${MEDIAGARRD_UPDATE_CHECK_INTERVAL:PT24H} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java index f817fe9..8f0185b 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/MediaGarrdPropertiesBindingTest.java @@ -11,7 +11,8 @@ @SpringBootTest(properties = { "mediagarrd.backup-root=${java.io.tmpdir}/mediagarrd-binding-test/backups", "mediagarrd.database-path=${java.io.tmpdir}/mediagarrd-binding-test/mediagarrd.db", - "mediagarrd.helper-image=alpine:3" + "mediagarrd.helper-image=alpine:3", + "mediagarrd.github-api-base-url=http://127.0.0.1:1" }) class MediaGarrdPropertiesBindingTest { @@ -27,5 +28,7 @@ void bindsApplicationProperties() { assertEquals(tmp + "/mediagarrd-binding-test/backups", properties.getBackupRoot()); assertEquals(tmp + "/mediagarrd-binding-test/mediagarrd.db", properties.getDatabasePath()); assertEquals("alpine:3", properties.getHelperImage()); + assertEquals("MediaGarrd/Server", properties.getUpdateRepository()); + assertEquals("http://127.0.0.1:1", properties.getGithubApiBaseUrl()); } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java index b9b3d5a..29f5e25 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/BackupControllerTest.java @@ -22,6 +22,7 @@ import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.service.BackupArchiveService; import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(BackupController.class) @@ -35,6 +36,9 @@ class BackupControllerTest { @MockBean BackupOrchestratorService orchestratorService; + @MockBean + RunStatusBroadcaster broadcaster; + @MockBean SetupService setup; @@ -107,4 +111,36 @@ void failedRunReturnsServerErrorWithReason() throws Exception { .andExpect(status().isInternalServerError()) .andExpect(jsonPath("$.error").value("Every service failed, no archive created: radarr: boom")); } + + @Test + void deletingABackupPublishesBackupsChanged() throws Exception { + when(archiveService.deleteById("backup-1")).thenReturn(true); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/backup-1")) + .andExpect(status().isNoContent()); + + org.mockito.Mockito.verify(broadcaster).publishBackupsChanged(); + } + + @Test + void deletingAMissingBackupPublishesNothing() throws Exception { + when(archiveService.deleteById("nope")).thenReturn(false); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete("/api/v1/backups/nope")) + .andExpect(status().isNotFound()); + + org.mockito.Mockito.verify(broadcaster, org.mockito.Mockito.never()).publishBackupsChanged(); + } + + @Test + void updatingTheSchedulePublishesConfigChanged() throws Exception { + when(orchestratorService.updateInterval(Duration.ofHours(2))).thenReturn(Duration.ofHours(2)); + + mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put("/api/v1/schedule") + .contentType(org.springframework.http.MediaType.APPLICATION_JSON) + .content("{\"backupInterval\": \"PT2H\"}")) + .andExpect(status().isOk()); + + org.mockito.Mockito.verify(broadcaster).publishConfigChanged(); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java index 8e59147..9fee6ce 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/ConfigControllerTest.java @@ -36,6 +36,7 @@ import wellatleastitried.mediagarrdServer.service.BackupOrchestratorService; import wellatleastitried.mediagarrdServer.service.DatabaseService; import wellatleastitried.mediagarrdServer.service.DockerService; +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; import wellatleastitried.mediagarrdServer.service.SetupService; @WebMvcTest(ConfigController.class) @@ -58,6 +59,9 @@ class ConfigControllerTest { @MockBean DockerService docker; + @MockBean + RunStatusBroadcaster broadcaster; + @MockBean SetupService setup; @@ -86,6 +90,8 @@ void rejectsConfigChangesWhileBackupIsRunning() throws Exception { verify(db, never()).addService(any()); verify(db, never()).removeService(anyString()); verify(archiveService, never()).updateSettings(any(), any()); + verify(broadcaster, never()).publishConfigChanged(); + verify(broadcaster, never()).publishBackupsChanged(); } @Test @@ -126,6 +132,8 @@ void updatesBackupLocationAndRetentionCount() throws Exception { .andExpect(jsonPath("$.retentionCount").value(4)); verify(archiveService).updateSettings("/new", 4); + verify(broadcaster).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -136,6 +144,8 @@ void passesOmittedFieldsAsNull() throws Exception { .andExpect(status().isOk()); verify(archiveService).updateSettings(isNull(), eq(4)); + verify(broadcaster, never()).publishBackupsChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -168,6 +178,8 @@ void addsNormalizedService() throws Exception { .andExpect(jsonPath("$.paths", hasSize(1))); verify(db).addService(RADARR); + verify(orchestrator).servicesChanged(); + verify(broadcaster).publishConfigChanged(); } @Test @@ -179,6 +191,8 @@ void rejectsDuplicateService() throws Exception { .andExpect(jsonPath("$.error").exists()); verify(db, never()).addService(any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); } @Test @@ -199,7 +213,9 @@ void updatesServiceKeepingContainersWhenNameUnchanged() throws Exception { .andExpect(jsonPath("$.paths[0]").value("/srv/other")); verify(db).updateService("radarr", new ServiceDefinition("radarr", List.of("/srv/other"))); + verify(orchestrator).servicesChanged(); verify(docker, never()).removeContainers(anyString()); + verify(broadcaster).publishConfigChanged(); } @Test @@ -223,6 +239,8 @@ void renamingOntoExistingServiceConflicts() throws Exception { .andExpect(status().isConflict()); verify(db, never()).updateService(anyString(), any()); + verify(orchestrator, never()).servicesChanged(); + verify(broadcaster, never()).publishConfigChanged(); } @Test @@ -231,6 +249,8 @@ void updatingMissingServiceReturnsNotFound() throws Exception { mockMvc.perform(json(put("/api/v1/services/radarr"), RADARR_JSON)) .andExpect(status().isNotFound()); + + verify(orchestrator, never()).servicesChanged(); } @Test @@ -242,6 +262,7 @@ void removesServiceAndItsContainers() throws Exception { verify(db).removeService("radarr"); verify(docker).removeContainers("radarr"); + verify(broadcaster).publishConfigChanged(); } @Test diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java new file mode 100644 index 0000000..e4c64e9 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/RunEventsControllerTest.java @@ -0,0 +1,72 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +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.web.servlet.mvc.method.annotation.SseEmitter; + +import wellatleastitried.mediagarrdServer.service.RunStatusBroadcaster; +import wellatleastitried.mediagarrdServer.service.SetupService; + +@Timeout(30) +@WebMvcTest(RunEventsController.class) +class RunEventsControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + RunStatusBroadcaster broadcaster; + + @MockBean + SetupService setup; + + @Test + void streamsEventsWithoutASetupSession() throws Exception { + when(setup.isCompleted()).thenReturn(false); + when(setup.canConfigure(null)).thenReturn(false); + when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()) + .andExpect(status().isOk()); + } + + @Test + void streamsEventsAfterSetupToo() throws Exception { + when(setup.isCompleted()).thenReturn(true); + when(broadcaster.subscribe()).thenReturn(new SseEmitter(60_000L)); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(request().asyncStarted()); + } + + @Test + void answers503WhenTooManySubscribers() throws Exception { + when(broadcaster.subscribe()).thenThrow(new RunStatusBroadcaster.SubscriberLimitException("full")); + + mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isServiceUnavailable()); + } + + @Test + void aTimedOutStreamEndsQuietlyWithoutAnErrorPage() throws Exception { + when(broadcaster.subscribe()).thenThrow(new org.springframework.web.context.request.async.AsyncRequestTimeoutException()); + + var result = mockMvc.perform(get("/api/v1/events").accept(MediaType.TEXT_EVENT_STREAM)) + .andExpect(status().isOk()) + .andReturn(); + + assertEquals("", result.getResponse().getContentAsString()); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java new file mode 100644 index 0000000..6027d77 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/api/VersionControllerTest.java @@ -0,0 +1,63 @@ +package wellatleastitried.mediagarrdServer.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Instant; + +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.test.web.servlet.MockMvc; + +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.dto.VersionStatusDto; +import wellatleastitried.mediagarrdServer.service.SetupService; +import wellatleastitried.mediagarrdServer.service.UpdateCheckService; + +@WebMvcTest(VersionController.class) +class VersionControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + UpdateCheckService updateCheckService; + + @MockBean + SetupService setup; + + @Test + void reportsTheVersionStatusWithoutASetupSession() throws Exception { + when(setup.isCompleted()).thenReturn(false); + when(setup.canConfigure(null)).thenReturn(false); + when(updateCheckService.status()).thenReturn(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)); + + mockMvc.perform(get("/api/v1/version")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.currentVersion").value("0.1.0")) + .andExpect(jsonPath("$.latestVersion").value("0.2.0")) + .andExpect(jsonPath("$.releaseUrl").value("https://github.com/MediaGarrd/Server/releases/tag/v0.2.0")) + .andExpect(jsonPath("$.updateAvailable").value(true)) + .andExpect(jsonPath("$.checkState").value("OK")) + .andExpect(jsonPath("$.checkedAt").value("2026-11-11T18:00:00Z")) + .andExpect(jsonPath("$.message").doesNotExist()); + } + + @Test + void reportsAFailedCheckAsAState() throws Exception { + when(updateCheckService.status()).thenReturn(new VersionStatusDto( + "0.1.0", null, null, false, CheckState.ERROR, Instant.parse("2026-11-11T18:00:00Z"), "GitHub is unreachable")); + + mockMvc.perform(get("/api/v1/version")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.checkState").value("ERROR")) + .andExpect(jsonPath("$.updateAvailable").value(false)) + .andExpect(jsonPath("$.message").value("GitHub is unreachable")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java index 33d03c2..a999d67 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupOrchestratorServiceTest.java @@ -7,6 +7,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -22,17 +24,21 @@ import java.util.concurrent.CompletableFuture; 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.Timeout; import org.mockito.ArgumentCaptor; +import wellatleastitried.mediagarrdServer.MediaGarrdProperties; import wellatleastitried.mediagarrdServer.model.BackupArchive; import wellatleastitried.mediagarrdServer.model.BackupRunResult; import wellatleastitried.mediagarrdServer.model.BackupServiceResult; import wellatleastitried.mediagarrdServer.model.ServiceDefinition; +@Timeout(30) class BackupOrchestratorServiceTest { private static final ServiceDefinition RADARR = new ServiceDefinition("radarr", List.of("/srv/radarr")); @@ -46,7 +52,8 @@ class BackupOrchestratorServiceTest { private final BackupScheduleService schedule = mock(BackupScheduleService.class); private final DatabaseService db = mock(DatabaseService.class); private final DatabaseSnapshotService snapshots = mock(DatabaseSnapshotService.class); - private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db); + private final RunStatusBroadcaster broadcaster = mock(RunStatusBroadcaster.class); + private final BackupOrchestratorService orchestrator = new BackupOrchestratorService(runner, archives, schedule, snapshots, db, broadcaster); @BeforeEach void setUp() { @@ -68,6 +75,62 @@ void refusesToRunWithoutServices() { verify(archives, never()).createRunDirectory(); assertFalse(orchestrator.isRunning()); + verify(broadcaster, never()).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + verify(schedule, never()).deferNextRun(); + } + + @Test + void aRejectedManualRunLeavesTheRealScheduleUntouched() { + MediaGarrdProperties properties = new MediaGarrdProperties(); + BackupScheduleService realSchedule = new BackupScheduleService(properties, db); + BackupOrchestratorService manual = new BackupOrchestratorService(runner, archives, realSchedule, snapshots, db, broadcaster); + when(db.fetchServices()).thenReturn(List.of()); + Instant before = realSchedule.getNextRun(); + + assertThrows(BackupOrchestratorService.RunRejectedException.class, manual::runBackup); + + assertEquals(before, realSchedule.getNextRun()); + manual.shutdownRunnerExecutor(); + } + + @Test + void aScheduledRunWithoutServicesDefersTheNextCheck() { + when(schedule.dueNow()).thenReturn(true); + when(db.fetchServices()).thenReturn(List.of()); + + orchestrator.scheduledRun(); + + verify(schedule).deferNextRun(); + verify(broadcaster, never()).publishStarted(any()); + } + + @Test + void aScheduledRunRejectedBecauseOneIsInProgressDoesNotDefer() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + when(schedule.dueNow()).thenReturn(true); + + CompletableFuture manual = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(BackupOrchestratorService.RunRejectedException.class, () -> orchestrator.runBackup(true)); + + verify(schedule, never()).deferNextRun(); + release.countDown(); + manual.get(5, TimeUnit.SECONDS); + } + + @Test + void changingServicesReleasesTheDeferral() { + orchestrator.servicesChanged(); + + verify(schedule).releaseDeferral(); } @Test @@ -271,6 +334,173 @@ void backupWaitsForInFlightConfigChange() throws Exception { assertEquals(COMPLETED, run.get(5, TimeUnit.SECONDS).status()); } + @Test + void publishesStartedBeforeWorkAndFinishedWithTheRunStatus() { + givenResults(COMPLETED, COMPLETED); + + orchestrator.runBackup(); + + var order = inOrder(broadcaster, runner, db); + order.verify(db).fetchServices(); + order.verify(broadcaster).publishStarted(any()); + order.verify(runner, org.mockito.Mockito.atLeastOnce()).run(any(), any()); + order.verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(any(), any(), any()); + } + + @Test + void publishesPartialWhenSomeServicesFail() { + givenResults(COMPLETED, FAILED); + + orchestrator.runBackup(); + + verify(broadcaster).publishFinished(eq(PARTIAL), any(), any()); + } + + @Test + void publishesFailedWhenEveryServiceFails() { + givenResults(FAILED, FAILED); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void publishesFailedWhenArchivingThrows() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + } + + @Test + void publishesFailedWhenTheRunDirectoryCannotBeCreated() { + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(archives.createRunDirectory()).thenThrow(new IllegalStateException("no space")); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishStarted(any()); + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void publishesFailedWhenRecordingTheRunThrows() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("db locked")).when(db).addNewBackupRecord(any()); + + assertThrows(IllegalStateException.class, orchestrator::runBackup); + + verify(broadcaster).publishFinished(eq(FAILED), any(), any()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void runningIsFalseWhenFinishedIsPublished() { + givenResults(COMPLETED, COMPLETED); + AtomicBoolean runningAtFinish = new AtomicBoolean(true); + doAnswer(invocation -> { + runningAtFinish.set(orchestrator.isRunning()); + return null; + }).when(broadcaster).publishFinished(any(), any(), any()); + + orchestrator.runBackup(); + + assertFalse(runningAtFinish.get()); + } + + @Test + void aFailingCleanupDoesNotStickTheRunningFlag() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + BackupRunResult result = orchestrator.runBackup(); + + assertEquals(COMPLETED, result.status()); + assertFalse(orchestrator.isRunning()); + verify(broadcaster).publishFinished(eq(COMPLETED), any(), any()); + assertEquals("changed", orchestrator.whileIdle(() -> "changed")); + assertEquals(COMPLETED, orchestrator.runBackup().status()); + } + + @Test + void aFailingCleanupDoesNotHideTheRunsOwnFailure() { + givenResults(COMPLETED, COMPLETED); + when(archives.createArchive(RUN_DIR)).thenThrow(new IllegalStateException("disk full")); + doThrow(new IllegalStateException("cannot delete")).when(archives).removeRunDirectory(RUN_DIR); + + IllegalStateException e = assertThrows(IllegalStateException.class, orchestrator::runBackup); + + assertEquals("disk full", e.getMessage()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aFailingPublishNeverBreaksTheRun() { + givenResults(COMPLETED, COMPLETED); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishStarted(any()); + doThrow(new IllegalStateException("boom")).when(broadcaster).publishFinished(any(), any(), any()); + + assertEquals(COMPLETED, orchestrator.runBackup().status()); + assertFalse(orchestrator.isRunning()); + } + + @Test + void aRejectedConcurrentRunPublishesNothingExtra() throws Exception { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + when(db.fetchServices()).thenReturn(List.of(RADARR)); + when(runner.run(eq(RADARR), any())).thenAnswer(invocation -> { + started.countDown(); + release.await(); + return result("radarr", COMPLETED); + }); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertThrows(BackupOrchestratorService.RunRejectedException.class, orchestrator::runBackup); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + verify(broadcaster, never()).publishFinished(any(), any(), any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + verify(broadcaster, org.mockito.Mockito.times(1)).publishFinished(eq(COMPLETED), any(), any()); + } + + @Test + void aFinishIsNeverOvertakenByTheNextRunsStart() throws Exception { + givenResults(COMPLETED, COMPLETED); + CountDownLatch inFinish = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + inFinish.countDown(); + release.await(); + return null; + }).doNothing().when(broadcaster).publishFinished(any(), any(), any()); + + CompletableFuture first = CompletableFuture.supplyAsync(orchestrator::runBackup); + assertTrue(inFinish.await(5, TimeUnit.SECONDS)); + CompletableFuture second = CompletableFuture.supplyAsync(orchestrator::runBackup); + Thread.sleep(200); + + assertFalse(second.isDone()); + verify(broadcaster, org.mockito.Mockito.times(1)).publishStarted(any()); + + release.countDown(); + first.get(5, TimeUnit.SECONDS); + second.get(5, TimeUnit.SECONDS); + var order = inOrder(broadcaster); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + order.verify(broadcaster).publishStarted(any()); + order.verify(broadcaster).publishFinished(any(), any(), any()); + } + private void givenResults(String radarrStatus, String sonarrStatus) { when(db.fetchServices()).thenReturn(List.of(RADARR, SONARR)); when(runner.run(RADARR, RUN_DIR)).thenReturn(result("radarr", radarrStatus)); diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java index e54ab04..ba05b43 100644 --- a/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/BackupScheduleServiceTest.java @@ -83,4 +83,41 @@ void ignoresCorruptStoredInterval() { db.saveSetting(BACKUP_INTERVAL_SETTING, "PT0S"); assertEquals(Duration.ofHours(2), new BackupScheduleService(properties, db).getInterval()); } + + @Test + void deferringTheNextRunStopsItBeingDueUntilTheIntervalElapses() throws Exception { + BackupScheduleService service = new BackupScheduleService(properties, db); + service.updateInterval(Duration.ofMillis(1)); + Thread.sleep(5); + assertTrue(service.dueNow()); + + service.updateInterval(Duration.ofHours(1)); + Thread.sleep(5); + service.deferNextRun(); + + assertFalse(service.dueNow()); + assertTrue(service.getNextRun().isAfter(java.time.Instant.now().plus(Duration.ofMinutes(59)))); + } + + @Test + void addingAServiceAfterADeferralMakesTheScheduleDueNow() { + BackupScheduleService service = new BackupScheduleService(properties, db); + service.deferNextRun(); + assertFalse(service.dueNow()); + + service.releaseDeferral(); + + assertTrue(service.dueNow()); + } + + @Test + void releasingWithoutADeferralChangesNothing() { + BackupScheduleService service = new BackupScheduleService(properties, db); + java.time.Instant before = service.getNextRun(); + + service.releaseDeferral(); + + assertEquals(before, service.getNextRun()); + assertFalse(service.dueNow()); + } } diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java new file mode 100644 index 0000000..ce5274b --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/RunStatusBroadcasterTest.java @@ -0,0 +1,356 @@ +package wellatleastitried.mediagarrdServer.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +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.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +@Timeout(30) +class RunStatusBroadcasterTest { + + private static final Instant STARTED = Instant.parse("2026-11-11T10:00:00Z"); + private static final Instant FINISHED = Instant.parse("2026-11-11T10:05:00Z"); + + private final CountDownLatch writerExited = new CountDownLatch(1); + private final List emitters = new ArrayList<>(); + private RunStatusBroadcaster broadcaster = newBroadcaster(16, 60_000); + + @AfterEach + void tearDown() { + broadcaster.shutdown(); + } + + @Test + void sendsTheCurrentStateFirstWhenIdle() throws Exception { + TestEmitter emitter = subscribe(); + + String frame = emitter.next(); + + assertTrue(frame.startsWith("event:state\ndata:{\"running\":false,\"at\":\""), frame); + assertTrue(frame.endsWith("\"}\n\n"), frame); + } + + @Test + void sendsRunningStateToLateSubscribers() throws Exception { + broadcaster.publishStarted(STARTED); + + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":true,\"at\":\"")); + + broadcaster.publishFinished("completed", STARTED, FINISHED); + + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":false,\"at\":\"")); + } + + @Test + void fansStartedAndFinishedOutToEverySubscriber() throws Exception { + TestEmitter first = subscribe(); + TestEmitter second = subscribe(); + first.next(); + second.next(); + + broadcaster.publishStarted(STARTED); + broadcaster.publishFinished("partial", STARTED, FINISHED); + + for (TestEmitter emitter : List.of(first, second)) { + assertEquals("event:run-started\ndata:{\"running\":true,\"startedAt\":\"2026-11-11T10:00:00Z\"}\n\n", emitter.next()); + assertEquals("event:run-finished\ndata:{\"running\":false,\"status\":\"PARTIAL\"," + + "\"startedAt\":\"2026-11-11T10:00:00Z\",\"finishedAt\":\"2026-11-11T10:05:00Z\"}\n\n", emitter.next()); + } + } + + @Test + void publishesBackupsAndConfigChangesWithoutTouchingTheRunState() throws Exception { + broadcaster.publishStarted(STARTED); + TestEmitter emitter = subscribe(); + assertTrue(emitter.next().startsWith("event:state\ndata:{\"running\":true")); + + broadcaster.publishBackupsChanged(); + broadcaster.publishConfigChanged(); + + String backups = emitter.next(); + String config = emitter.next(); + assertTrue(backups.matches("event:backups-changed\\ndata:\\{\"at\":\"[^\"]+\"\\}\\n\\n"), backups); + assertTrue(config.matches("event:config-changed\\ndata:\\{\"at\":\"[^\"]+\"\\}\\n\\n"), config); + assertTrue(subscribe().next().startsWith("event:state\ndata:{\"running\":true")); + } + + @Test + void changeNoticesNeverBlockOnAStuckSubscriber() throws Exception { + TestEmitter stuck = new TestEmitter(); + stuck.blockSends = new CountDownLatch(1); + broadcaster.subscribe(stuck); + emitters.add(stuck); + assertTrue(stuck.sendEntered.await(5, TimeUnit.SECONDS)); + + CompletableFuture.runAsync(() -> { + for (int i = 0; i < 40; i++) { + broadcaster.publishBackupsChanged(); + broadcaster.publishConfigChanged(); + } + }).get(5, TimeUnit.SECONDS); + + awaitCount(0); + stuck.blockSends.countDown(); + } + + @Test + void sendsANamedPingWhenIdle() throws Exception { + broadcaster = newBroadcaster(16, 30); + TestEmitter emitter = subscribe(); + emitter.next(); + + assertEquals("event:ping\ndata:{}\n\n", emitter.next()); + assertEquals("event:ping\ndata:{}\n\n", emitter.next()); + } + + @Test + void rejectsSubscribersBeyondTheCap() { + broadcaster = newBroadcaster(2, 60_000); + subscribe(); + subscribe(); + + assertThrows(RunStatusBroadcaster.SubscriberLimitException.class, () -> broadcaster.subscribe(new TestEmitter())); + assertEquals(2, broadcaster.subscriberCount()); + } + + @Test + void completionFreesASlot() throws Exception { + broadcaster = newBroadcaster(1, 60_000); + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.completion.get().run(); + + awaitCount(0); + subscribe(); + } + + @Test + void errorFreesASlotWithoutCompletingAgain() throws Exception { + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.error.get().accept(new IOException("reset")); + + awaitCount(0); + assertTrue(writerExited.await(5, TimeUnit.SECONDS)); + assertEquals(1, emitter.completes.getCount()); + assertEquals(1, emitter.errors.getCount()); + } + + @Test + void timeoutCompletesTheEmitterOnTheWriterThread() throws Exception { + TestEmitter emitter = subscribe(); + emitter.next(); + + emitter.timeout.get().run(); + + assertTrue(emitter.completes.await(5, TimeUnit.SECONDS)); + assertTrue(emitter.completedOn.get().startsWith("run-events-writer-"), emitter.completedOn.get()); + awaitCount(0); + } + + @Test + void aFailingSendDropsOnlyThatSubscriber() throws Exception { + TestEmitter broken = subscribe(); + TestEmitter healthy = subscribe(); + healthy.next(); + broken.failSends = true; + + broadcaster.publishStarted(STARTED); + + assertTrue(healthy.next().startsWith("event:run-started")); + awaitCount(1); + assertTrue(broken.errors.await(5, TimeUnit.SECONDS)); + } + + @Test + void publishingNeverBlocksOnASubscriberStuckInAWrite() throws Exception { + TestEmitter stuck = new TestEmitter(); + stuck.blockSends = new CountDownLatch(1); + broadcaster.subscribe(stuck); + emitters.add(stuck); + assertTrue(stuck.sendEntered.await(5, TimeUnit.SECONDS)); + + long begin = System.nanoTime(); + CompletableFuture publishing = CompletableFuture.runAsync(() -> { + for (int i = 0; i < 40; i++) { + broadcaster.publishStarted(STARTED); + broadcaster.publishFinished("completed", STARTED, FINISHED); + } + }); + publishing.get(5, TimeUnit.SECONDS); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin); + + assertTrue(elapsedMs < 1000, "publish took " + elapsedMs + "ms"); + awaitCount(0); + assertEquals(1, stuck.completes.getCount()); + + stuck.blockSends.countDown(); + assertTrue(stuck.completes.await(5, TimeUnit.SECONDS)); + assertTrue(stuck.completedOn.get().startsWith("run-events-writer-"), stuck.completedOn.get()); + } + + @Test + void shutdownCompletesEverySubscriberAndRefusesNewOnes() throws Exception { + TestEmitter first = subscribe(); + TestEmitter second = subscribe(); + first.next(); + second.next(); + + broadcaster.shutdown(); + + assertTrue(first.completes.await(5, TimeUnit.SECONDS)); + assertTrue(second.completes.await(5, TimeUnit.SECONDS)); + assertEquals(0, broadcaster.subscriberCount()); + assertThrows(RunStatusBroadcaster.SubscriberLimitException.class, () -> broadcaster.subscribe(new TestEmitter())); + } + + @Test + void createsAnEmitterWithAFiniteTimeout() { + RunStatusBroadcaster real = new RunStatusBroadcaster(); + try { + SseEmitter emitter = real.subscribe(); + assertNotNull(emitter); + assertEquals(RunStatusBroadcaster.EMITTER_TIMEOUT_MS, emitter.getTimeout()); + } finally { + real.shutdown(); + } + } + + @Test + void theWriterEndsTheStreamItselfAtTheRolloverAge() throws Exception { + broadcaster.shutdown(); + broadcaster = new RunStatusBroadcaster(16, 60_000, 20, 150, runnable -> { + Thread thread = new Thread(runnable, "run-events-writer-test"); + thread.setDaemon(true); + return thread; + }); + TestEmitter emitter = subscribe(); + emitter.next(); + + assertTrue(emitter.completes.await(5, TimeUnit.SECONDS)); + assertEquals(1, emitter.errors.getCount()); + assertTrue(emitter.completedOn.get().startsWith("run-events-writer-"), emitter.completedOn.get()); + awaitCount(0); + } + + @Test + void rolloverComesBeforeTheEmitterTimeout() { + assertTrue(RunStatusBroadcaster.ROLLOVER_MS < RunStatusBroadcaster.EMITTER_TIMEOUT_MS); + } + + private RunStatusBroadcaster newBroadcaster(int cap, long pingMs) { + return new RunStatusBroadcaster(cap, 60_000, pingMs, 60_000, runnable -> { + Thread thread = new Thread(() -> { + try { + runnable.run(); + } finally { + writerExited.countDown(); + } + }, "run-events-writer-test"); + thread.setDaemon(true); + return thread; + }); + } + + private TestEmitter subscribe() { + TestEmitter emitter = new TestEmitter(); + emitters.add(emitter); + broadcaster.subscribe(emitter); + return emitter; + } + + private void awaitCount(int expected) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (broadcaster.subscriberCount() != expected && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals(expected, broadcaster.subscriberCount()); + } + + static class TestEmitter extends SseEmitter { + + final BlockingQueue frames = new LinkedBlockingQueue<>(); + final CountDownLatch completes = new CountDownLatch(1); + final CountDownLatch errors = new CountDownLatch(1); + final CountDownLatch sendEntered = new CountDownLatch(1); + final AtomicReference timeout = new AtomicReference<>(); + final AtomicReference completion = new AtomicReference<>(); + final AtomicReference> error = new AtomicReference<>(); + final AtomicReference completedOn = new AtomicReference<>(); + volatile boolean failSends; + volatile CountDownLatch blockSends; + + TestEmitter() { + super(60_000L); + } + + String next() throws InterruptedException { + String frame = frames.poll(5, TimeUnit.SECONDS); + assertNotNull(frame, "no frame received"); + return frame; + } + + @Override + public synchronized void send(SseEventBuilder builder) throws IOException { + sendEntered.countDown(); + if (blockSends != null) { + try { + blockSends.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + if (failSends) { + throw new IOException("broken pipe"); + } + StringBuilder frame = new StringBuilder(); + builder.build().forEach(part -> frame.append(part.getData())); + frames.add(frame.toString()); + } + + @Override + public void complete() { + completedOn.set(Thread.currentThread().getName()); + completes.countDown(); + } + + @Override + public void completeWithError(Throwable ex) { + errors.countDown(); + } + + @Override + public void onTimeout(Runnable callback) { + timeout.set(callback); + } + + @Override + public void onCompletion(Runnable callback) { + completion.set(callback); + } + + @Override + public void onError(Consumer callback) { + error.set(callback); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java b/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java new file mode 100644 index 0000000..1488833 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/service/UpdateCheckServiceTest.java @@ -0,0 +1,285 @@ +package wellatleastitried.mediagarrdServer.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.mediagarrdServer.MediaGarrdProperties; +import wellatleastitried.mediagarrdServer.dto.CheckState; +import wellatleastitried.mediagarrdServer.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 MediaGarrdProperties properties = new MediaGarrdProperties(); + 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/Server"); + } + + @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/Server/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 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/Server/releases/tag/v0.2.0", true, CheckState.OK, NOW, null), service.status()); + assertEquals(List.of("/repos/MediaGarrd/Server/releases/latest"), requests); + assertEquals(List.of("MediaGarrd-Server/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/Server/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/mediagarrdServer/utilities/SemVerTest.java b/src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java new file mode 100644 index 0000000..0d1c1f5 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdServer/utilities/SemVerTest.java @@ -0,0 +1,66 @@ +package wellatleastitried.mediagarrdServer.utilities; + +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()); + } +}