diff --git a/TODO.adoc b/TODO.adoc index 3e3c4fb..b7592c2 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -229,6 +229,26 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho ** [ ] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the browser's GNSS control), the dashboard as part of the driving-mode UI ** [ ] `locate()` scans the whole route each fix — a window around the last hit on long routes +** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet + or display in the back, phones): the co-driver adds a stop, the driver's view reroutes on the + fly without losing the map (no stop / reload / start like Android Auto between two phones) +*** [x] `TripStore` (`lib/maptool/trip.rb`, `data/trip.json`): points, vehicle, avoids, the + library route being edited and the route, versioned; `GET /api/trip?version=N` (204 while + unchanged), `PUT /api/trip` routes it on the server (not again when only names/nav + changed). Logged in, the route panel edits it and polls it every 2 s — other screens' + changes swapped in, the camera untouched, the old route shown until the new one is in +*** [ ] Rerouting on the server: it has the GNSS (CAN), so off-route detection and the new + route once for all screens, not per screen with a dashboard (today's, `dashboard.js`) +*** [ ] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg + times), "Add to the trip" from search, the library, park4night and other sources +*** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with + the library sync, or "send to the car") +*** [ ] Push instead of polling (SSE) if 2 s ever feels slow +** [ ] Android Auto: the browser can't be cast there, only a native app — a small one with + the Car App Library's NavigationTemplate drawing its own map surface (MapLibre Native) off + the car server's trip and position (`/api/trip`, `/api/gnss/position`); only the map and + the next maneuver, planning stays on the web. Testable without the car: the tablet runs the + Android Auto head unit emulation (DHU) ** [ ] A native Android app on Ferrostar (rerouting, Valhalla speed limits, TTS built in) over our Valhalla (`format: osrm`) — only if navigation is wanted on a phone outside the car; the car's 16" display is the Pi's browser either way. Ferrostar's web components are beta: no diff --git a/app.rb b/app.rb index ecd2b91..06618b1 100644 --- a/app.rb +++ b/app.rb @@ -13,6 +13,8 @@ require_relative "lib/maptool/routing" require_relative "lib/maptool/mqtt_client" require_relative "lib/maptool/can" require_relative "lib/maptool/gnss_sim" +require_relative "lib/maptool/trip" +require_relative "lib/maptool/updater" require_relative "lib/maptool/sync" require "ipaddr" require_relative "lib/maptool/live_store" @@ -492,6 +494,33 @@ module Maptool redirect "/", 303 end + # Self-update (lib/maptool/updater.rb), on the car's server only + # (SELF_UPDATE=1): GET says whether main has a newer commit that passed + # CI, POST asks the host to install it (bin/update-maptool.sh). + SELF_UPDATE = ENV["SELF_UPDATE"] == "1" + UPDATE_REPO = ENV.fetch("UPDATE_REPO", "randy/maptool") + + get "/api/update" do + require_login! + halt json(enabled: false) unless SELF_UPDATE + + latest = Updater.latest(GITEA_URL, UPDATE_REPO) + available = !!latest && latest[:ci] == "success" && latest[:sha] && !latest[:sha].start_with?(REVISION) + json enabled: true, current: REVISION, latest: latest&.dig(:sha)&.slice(0, 7), ci: latest&.dig(:ci), + available: available, status: Updater.status(DATA_DIR) + end + + post "/api/update" do + require_login! + halt 404, json(error: "self-update is off on this server") unless SELF_UPDATE + + latest = Updater.latest(GITEA_URL, UPDATE_REPO) + halt 409, json(error: "no newer version that passed CI") unless latest && latest[:ci] == "success" && !latest[:sha].start_with?(REVISION) + + Updater.request(DATA_DIR, latest[:sha]) + json requested: latest[:sha][0, 7] + end + get "/api/health" do json status: "ok", revision: REVISION end @@ -680,6 +709,34 @@ module Maptool halt 503, json(error: e.message) end + # The shared trip (lib/maptool/trip.rb): every screen polls it + # (?version=N: 204 while it's still N) and edits it with PUT + # {points: [{lngLat, name, nav}], vehicle, avoid, editing}, routed here. + # Logged in only — it's this server's own itinerary. + TRIP_STORE = TripStore.new(File.join(DATA_DIR, "trip.json")) + + get "/api/trip" do + require_login! + trip = TRIP_STORE.get + halt 204 if params[:version] && params[:version].to_i == trip[:version] + + json trip + end + + put "/api/trip" do + require_login! + body = JSON.parse(request.body.read, symbolize_names: true) + halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) } + + json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing]) do |locations, vehicle, avoid| + Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s)) + end) + rescue JSON::ParserError + halt 400, json(error: "invalid JSON") + rescue ArgumentError, TypeError, KeyError + halt 400, json(error: "invalid points") + end + # The road being driven ({"points": [[lon, lat], ...]}, the last few # fixes): name and speed limit, for the dashboard. Open like /api/route. post "/api/road" do diff --git a/bin/update-maptool.sh b/bin/update-maptool.sh new file mode 100755 index 0000000..7ba774d --- /dev/null +++ b/bin/update-maptool.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# The car's server updating itself, when asked from the app: the update +# button (POST /api/update) writes data/update/request.json with the commit, +# maptool-update.path runs this as root (the container writes data/ as root). +# Downloads that commit's tree from Gitea (the repo is public: no token), +# swaps it into build/ (the old one kept as build.old) and restarts maptool; +# data/update/status.json tells the app how far it got. docs/deployment.adoc. +set -euo pipefail + +ROOT=${MAPTOOL_ROOT:-/srv/podman/maptool} +REPO_URL=${REPO_URL:-https://git.priesol.net/randy/maptool} +DIR=$ROOT/data/update +req=$DIR/request.json + +[ -f "$req" ] || exit 0 +sha=$(sed -n 's/.*"sha" *: *"\([0-9a-f]\{40\}\)".*/\1/p' "$req") +rm -f "$req" + +status() { + printf '{"state":"%s","sha":"%s","message":"%s","at":%s}\n' "$1" "$sha" "$2" "$(date +%s)" > "$DIR/status.json.tmp" + mv "$DIR/status.json.tmp" "$DIR/status.json" +} +fail() { status failed "$1"; echo "update-maptool: $1" >&2; exit 1; } + +[ -n "$sha" ] || fail "no commit in the request" +status running "downloading ${sha:0:7}" +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +curl -fsS --retry 3 --retry-delay 5 --speed-limit 1024 --speed-time 60 -o "$tmp/src.tar.gz" "$REPO_URL/archive/$sha.tar.gz" \ + || fail "download of ${sha:0:7} failed" +mkdir "$tmp/build" +tar -xzf "$tmp/src.tar.gz" -C "$tmp/build" --strip-components=1 || fail "the archive didn't unpack" +[ -f "$tmp/build/app.rb" ] || fail "not a maptool tree" +echo "${sha:0:7}" > "$tmp/build/REVISION" +chown -R --reference="$ROOT" "$tmp/build" + +rm -rf "$ROOT/build.old" +mv "$ROOT/build" "$ROOT/build.old" +mv "$tmp/build" "$ROOT/build" +status restarting "restarting with ${sha:0:7}" +systemctl restart podman-compose@maptool.service +status done "updated to ${sha:0:7}" diff --git a/docs/deployment.adoc b/docs/deployment.adoc index d28db92..978aa49 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -191,6 +191,40 @@ Its `.env` adds: never on brick, where every request comes from the proxy. * `TAKEOUT_HOST_DIR` — an empty directory (the Takeout import is brick's). * `SYNC_SERVER_URL` (`https://map.priesol.net`) and `SYNC_TOKEN`: it's a sync client. +* `SELF_UPDATE=1` — the update button (below). + +=== Updates (a button, not CI) + +CI deploys brick only: the car's server is often offline, and a deploy +mustn't restart it mid-drive. Instead it checks Gitea itself (every +10 min while online; the repo is public, no token): when `main` has a +newer commit whose CI passed, a ⟳ button shows in the topbar; a click +writes `data/update/request.json`, `maptool-update.path` starts +`bin/update-maptool.sh` (as root — the container writes `data/` as root), +which downloads that commit's archive from Gitea, swaps it into `build/` +(the previous one stays as `build.old/`), restarts maptool and reports in +`data/update/status.json`; the page reloads on the new revision. + +---- +# /etc/systemd/system/maptool-update.path +[Unit] +Description=Update maptool when the app asks +[Path] +PathExists=/srv/podman/maptool/data/update/request.json +[Install] +WantedBy=multi-user.target + +# /etc/systemd/system/maptool-update.service +[Unit] +Description=Update maptool to the commit the app asked for +After=network-online.target +[Service] +Type=oneshot +ExecStart=/srv/podman/maptool/build/bin/update-maptool.sh +---- + +`systemctl enable --now maptool-update.path`. Back by hand: +`mv build build.bad && mv build.old build`, restart. === Library sync (both ways, OsmAnd-style) diff --git a/lib/maptool/gnss_sim.rb b/lib/maptool/gnss_sim.rb index 52b2257..97d7ce2 100644 --- a/lib/maptool/gnss_sim.rb +++ b/lib/maptool/gnss_sim.rb @@ -16,8 +16,10 @@ module Maptool attr_reader :error - def initialize(valhalla_url, vehicle: { id: "car" }, random: Random.new, sleep: ->(s) { Kernel.sleep(s) }) + def initialize(valhalla_url, vehicle: { id: "car" }, random: Random.new, sleep: ->(s) { Kernel.sleep(s) }, + router: Routing.method(:route)) @valhalla_url = valhalla_url + @router = router @vehicle = vehicle @random = random @sleep = sleep @@ -30,6 +32,9 @@ module Maptool end RANDOM_START_TRIES = 20 # a random point at sea / off the routing tiles: another one + # Shorter: a road island the start snapped to (a lake's middle → a 0 km + # route), it'd drive the same few meters again and again — another try. + MIN_TRIP_KM = 1.0 # Drives from [lon, lat] until stopped — or, with bboxes # ([[west, south, east, north], ...], the offline countries) instead, @@ -44,6 +49,10 @@ module Maptool loop do position = drive(position, route, &on_fix) route = nil + rescue Routing::RouteError + raise unless bboxes + + position, route = random_start(bboxes) # no way on from here: somewhere else end rescue StandardError => e @error = e.message @@ -104,8 +113,10 @@ module Maptool distance = @random.rand(DEST_KM) * 1000 lon, lat = position dest = [lon + distance * Math.sin(bearing) / (111_320 * Math.cos(lat * Math::PI / 180)), lat + distance * Math.cos(bearing) / 111_320] - route = Routing.route(@valhalla_url, [position, dest], @vehicle) - return route if route[:geometry][:coordinates].size >= 2 + route = @router.call(@valhalla_url, [position, dest], @vehicle) + return route if route[:geometry][:coordinates].size >= 2 && route[:properties][:distance_km].to_f >= MIN_TRIP_KM + + last = Routing::RouteError.new("only #{route[:properties][:distance_km]} km") rescue Routing::RouteError => e last = e end diff --git a/lib/maptool/trip.rb b/lib/maptool/trip.rb new file mode 100644 index 0000000..c645c5b --- /dev/null +++ b/lib/maptool/trip.rb @@ -0,0 +1,56 @@ +require "json" +require_relative "routing" + +module Maptool + # The trip being driven, one for every screen of this server (the cab's + # display, the tablet in the back, the phone): its points, vehicle and + # avoids, and the route through them. Any screen edits it (PUT + # /api/trip), the server routes it again and bumps the version; every + # screen polls GET /api/trip and swaps the route in without touching its + # camera. Kept in data/trip.json across restarts. + class TripStore + EMPTY = { version: 0, points: [], vehicle: nil, avoid: {}, editing: nil, route: nil, error: nil }.freeze + + def initialize(path) + @path = path + @mutex = Mutex.new + @trip = begin + EMPTY.merge(JSON.parse(File.read(path), symbolize_names: true)) + rescue Errno::ENOENT, JSON::ParserError + EMPTY.dup + end + end + + def get + @mutex.synchronize { @trip.dup } + end + + # points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them with + # the block (locations, vehicle id, avoid → the /api/route Feature, may + # raise Routing errors) unless only names/nav changed — the old route + # stays then. Last write wins. + def update(points:, vehicle:, avoid:, editing:) + points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav] } } + avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] } + before = get + same_route = before[:points].map { |p| p[:lngLat] } == points.map { |p| p[:lngLat] } && + before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error] + route, error = if same_route then [before[:route], nil] + elsif points.size < 2 then [nil, nil] + else + begin + [yield(points.map { |p| p[:lngLat] }, vehicle, avoid), nil] + rescue Routing::RouteError, Routing::Unavailable => e + [nil, e.message] + end + end + @mutex.synchronize do + @trip = { version: @trip[:version] + 1, points: points, vehicle: vehicle, avoid: avoid, editing: editing, + route: route, error: error, updated_at: Time.now.to_f } + File.write("#{@path}.tmp", JSON.generate(@trip)) + File.rename("#{@path}.tmp", @path) + @trip.dup + end + end + end +end diff --git a/lib/maptool/updater.rb b/lib/maptool/updater.rb new file mode 100644 index 0000000..8ab6056 --- /dev/null +++ b/lib/maptool/updater.rb @@ -0,0 +1,58 @@ +require "json" +require "fileutils" +require "net/http" + +module Maptool + # Self-update of the car's server (SELF_UPDATE=1; brick deploys by CI): + # is there a newer commit on main that passed CI (Gitea's API, the repo + # is public), and asking the host to install it — data/update/request.json, + # picked up by maptool-update.path → bin/update-maptool.sh, which reports + # back in data/update/status.json. + module Updater + CHECK_EVERY_S = 600 + MUTEX = Mutex.new + + def self.dir(data_dir) + File.join(data_dir, "update") + end + + # { sha:, ci: "success" | "pending" | "failure" | … } of main, cached + # CHECK_EVERY_S; nil while Gitea can't be reached (no internet on the road). + def self.latest(gitea_url, repo, fetch: method(:get_json)) + MUTEX.synchronize do + return @latest if @checked_at && Time.now.to_f - @checked_at < CHECK_EVERY_S + + @checked_at = Time.now.to_f + sha = fetch.call("#{gitea_url}/api/v1/repos/#{repo}/branches/main").dig("commit", "id") + @latest = { sha: sha, ci: fetch.call("#{gitea_url}/api/v1/repos/#{repo}/commits/#{sha}/status")["state"] } + rescue StandardError + @latest = nil + end + end + + def self.reset! + MUTEX.synchronize { @checked_at = @latest = nil } + end + + def self.request(data_dir, sha) + raise ArgumentError, "not a commit" unless sha.to_s.match?(/\A[0-9a-f]{40}\z/) + + FileUtils.mkdir_p(dir(data_dir)) + File.write(File.join(dir(data_dir), "request.json"), JSON.generate(sha: sha, at: Time.now.to_i)) + end + + def self.status(data_dir) + JSON.parse(File.read(File.join(dir(data_dir), "status.json")), symbolize_names: true) + rescue Errno::ENOENT, JSON::ParserError + nil + end + + def self.get_json(url) + uri = URI(url) + response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) { |http| http.get(uri.request_uri) } + raise "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess) + + JSON.parse(response.body) + end + end +end diff --git a/public/css/style.css b/public/css/style.css index 64c42c4..5f3d1a4 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -276,6 +276,20 @@ html, body { background: #2a9d8f; } +/* A newer version for the car's server (public/js/update.js). */ +.topbar__update { + height: 32px; + padding: 0 10px; + border: none; + border-radius: 6px; + background: #2a9d8f; + color: #fff; + font-size: 13px; + font-weight: 600; + cursor: pointer; +} +.topbar__update:disabled { opacity: 0.7; cursor: progress; } + .topbar__auth { margin-left: auto; display: flex; diff --git a/public/js/map.js b/public/js/map.js index e764f14..41e3404 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -23,6 +23,7 @@ import { getPosition } from "/vendor/suncalc/suncalc.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen, setupSidePanelModes } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; import { DebugControl } from "/js/debug.js"; +import { setupUpdate } from "/js/update.js"; import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap } from "/js/map_themes.js"; import { offerSharedFiles } from "/js/share_import.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; @@ -555,6 +556,7 @@ gnssControl.mount(sidebar); new LiveTrackPanelControl(map).mount(sidebar); if (isLoggedIn()) new DebugControl().mount(sidebar); +if (isLoggedIn()) setupUpdate(document.querySelector(".topbar__update")); setupSidePanelModes(); // The sidebar already has a "Base map" icon (opens the same panel) — diff --git a/public/js/route.js b/public/js/route.js index 6e9fe7a..17060c1 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -6,6 +6,12 @@ import { wirePreview } from "/js/preview.js"; import { elevationAt } from "/js/dem.js"; const ROUTE_URL = "/api/route"; +// Logged in, the panel edits this server's shared trip (lib/maptool/trip.rb) +// instead of a route of its own: every change goes there (routed by the +// server), and other screens' changes come in by polling — the points, +// vehicle, avoids and route swapped in, the camera left where it is. +const TRIP_URL = "/api/trip"; +const TRIP_POLL_MS = 2000; const ISOCHRONE_URL = "/api/isochrone"; const REACH_SOURCE = "route-reach"; const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart @@ -40,6 +46,8 @@ export class RoutePanelControl { this._route = null; // the last /api/route Feature this._request = 0; // so a slow older response can't overwrite a newer one this._editing = null; // { key, id, name } of a saved route being edited + this._version = -1; // the shared trip's, -1: not loaded yet + this._pushing = 0; // PUTs in flight: polls wait for them // Rerouting (the dashboard, off the route): the start and the via points // already passed give way to the current position. @@ -105,6 +113,74 @@ export class RoutePanelControl { onlyOneSidePanelOpen(this._panel, () => this._setOpen(false)); sidebar.appendChild(this._container); + + this._shared = isLoggedIn(); + if (this._shared) { + this._pollTrip(); + setInterval(() => this._pollTrip(), TRIP_POLL_MS); + } + } + + // --- shared trip ------------------------------------------------------------ + + async _pollTrip() { + if (this._pushing) return; + try { + const response = await fetch(`${TRIP_URL}?version=${this._version}`, { cache: "no-store" }); + if (response.status !== 200) return; // 204: unchanged + const trip = await response.json(); + if (!this._pushing && trip.version > this._version) this._applyTrip(trip, true); + } catch { + // offline for a moment: the next poll + } + } + + async _pushTrip() { + const request = ++this._request; + this._pushing++; + // the old route stays on the map (the driver's view) until the new one is in + if (this._points.length >= 2) this._summary.textContent = "Routing…"; + try { + const response = await fetch(TRIP_URL, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + points: this._points.map(({ lngLat, name, nav }) => ({ lngLat, name, nav })), + vehicle: this._vehicleId, + avoid: this._avoid, + editing: this._editing, + }), + }); + const trip = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(trip.error || `HTTP ${response.status}`); + if (request === this._request) this._applyTrip(trip, false); + } catch (err) { + if (request === this._request) this._showResult(null, `Not saved: ${err.message}`); + } finally { + this._pushing--; + } + } + + // The server's trip into the panel: its route always, its points (and + // vehicle, avoids, the library route being edited) when they came from + // another screen. + _applyTrip(trip, fromElsewhere) { + this._version = trip.version; + if (fromElsewhere) { + this._points.forEach((p) => p.marker.remove()); + this._points = []; + trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav })); + this._editing = trip.editing; + this._avoid = { ...trip.avoid }; + this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name])); + if (trip.vehicle && trip.vehicle !== this._vehicleId) { + if (this._selectVehicle) this._selectVehicle(trip.vehicle); + else this._vehicleId = trip.vehicle; + } + this._renderPoints(); + } + this._route = trip.route; + this._showResult(trip.route, trip.error ? `No route: ${trip.error}` : ""); } _togglePanel(force) { @@ -226,6 +302,7 @@ export class RoutePanelControl { } point.nav = !point.nav; this._renderPoints(); + if (this._shared) this._pushTrip(); // the server keeps the route, only the flag changes }); button.classList.add("route-panel__nav"); button.classList.toggle("active", !!point.nav); @@ -248,6 +325,7 @@ export class RoutePanelControl { // --- route ---------------------------------------------------------------- async _fetchRoute() { + if (this._shared) return this._pushTrip(); const request = ++this._request; this._route = null; if (this._points.length < 2) { @@ -599,7 +677,8 @@ export class RoutePanelControl { }; try { - this._vehicleId = localStorage.getItem(VEHICLE_KEY); + // the shared trip's vehicle, when it came in before the vehicles did + this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY); } catch {} fill(); select.addEventListener("change", () => { diff --git a/public/js/update.js b/public/js/update.js new file mode 100644 index 0000000..b5c01aa --- /dev/null +++ b/public/js/update.js @@ -0,0 +1,52 @@ +// The car's server updating itself (GET/POST /api/update, SELF_UPDATE=1 in +// its .env): a topbar button shows up when main has a newer version that +// passed CI; a click installs it (bin/update-maptool.sh on the host) and the +// page reloads once the server answers with the new revision. +const CHECK_MS = 10 * 60 * 1000; +const RESTART_POLL_MS = 5000; + +export function setupUpdate(button) { + let latest = null; + + async function check() { + try { + const state = await (await fetch("/api/update", { cache: "no-store" })).json(); + if (!state.enabled) return; + latest = state.latest; + button.hidden = !state.available; + button.textContent = `⟳ ${state.latest}`; + button.title = `A new version (${state.latest}, now ${state.current}) — click to update; the app restarts for about a minute`; + if (state.status?.state === "failed") button.title += `\nThe last update failed: ${state.status.message}`; + setTimeout(check, CHECK_MS); + } catch { + setTimeout(check, CHECK_MS); + } + } + + async function waitForRestart(revision) { + try { + const health = await (await fetch("/api/health", { cache: "no-store" })).json(); + if (health.revision !== revision) return window.location.reload(); + } catch { + // restarting: not answering for a while + } + setTimeout(() => waitForRestart(revision), RESTART_POLL_MS); + } + + button.addEventListener("click", async () => { + if (!window.confirm(`Update to ${latest}? The app restarts — about a minute without it.`)) return; + button.disabled = true; + button.textContent = "Updating…"; + const response = await fetch("/api/update", { method: "POST" }); + const data = await response.json().catch(() => ({})); + if (!response.ok) { + window.alert(data.error || `Update failed (${response.status})`); + button.disabled = false; + return check(); + } + const revision = (await (await fetch("/api/health")).json()).revision; + waitForRestart(revision); + }); + + check(); +} diff --git a/test/test_gnss_sim.rb b/test/test_gnss_sim.rb index fa5077b..027dd93 100644 --- a/test/test_gnss_sim.rb +++ b/test/test_gnss_sim.rb @@ -30,7 +30,7 @@ class GnssSimTest < Minitest::Test (@tried ||= []) << position raise Maptool::Routing::RouteError, "no road" if @tried.size == 1 - { geometry: { coordinates: [position, position] }, properties: {} } + { geometry: { coordinates: [position, position] }, properties: { distance_km: 5 } } end end @@ -41,4 +41,13 @@ class GnssSimTest < Minitest::Test assert position[0].between?(17.0, 18.0) && position[1].between?(48.0, 49.0) assert_equal position, route[:geometry][:coordinates].first end + + def test_a_route_under_a_km_is_another_try_and_none_at_all_an_error + lengths = [0.0, 0.2, 3.0] + router = ->(*) { { geometry: { coordinates: [[1, 2], [1, 3]] }, properties: { distance_km: lengths.shift } } } + sim = Maptool::GnssSim.new("http://valhalla", router: router) + assert_equal 3.0, sim.random_route([1, 2])[:properties][:distance_km] + lengths = [0.0] * 5 + assert_raises(Maptool::Routing::RouteError) { sim.random_route([1, 2]) } + end end diff --git a/test/test_trip.rb b/test/test_trip.rb new file mode 100644 index 0000000..21572ba --- /dev/null +++ b/test/test_trip.rb @@ -0,0 +1,38 @@ +require_relative "test_helper" +require "tmpdir" +require_relative "../lib/maptool/trip" + +class TripTest < Minitest::Test + def test_an_update_routes_bumps_the_version_and_survives_a_restart + Dir.mktmpdir do |dir| + path = File.join(dir, "trip.json") + store = Maptool::TripStore.new(path) + assert_equal 0, store.get[:version] + points = [{ lngLat: [17.1, 48.1], name: "Home" }, { lngLat: [17.2, 48.2] }] + calls = [] + router = ->(locations, vehicle, avoid) { calls << [locations, vehicle, avoid]; { type: "Feature", km: 1 } } + trip = store.update(points: points, vehicle: "camper", avoid: { tolls: true }, editing: nil, &router) + assert_equal [1, { type: "Feature", km: 1 }], trip.values_at(:version, :route) + assert_equal [[[[17.1, 48.1], [17.2, 48.2]], "camper", { tolls: true }]], calls + + # only a name/nav changed: no routing, the route stays + points[1] = { lngLat: [17.2, 48.2], name: "Camp", nav: true } + trip = store.update(points: points, vehicle: "camper", avoid: { tolls: true }, editing: nil, &router) + assert_equal [2, 1, "Camp"], [trip[:version], calls.size, trip[:points][1][:name]] + + reloaded = Maptool::TripStore.new(path).get + assert_equal [2, { type: "Feature", km: 1 }, "Camp"], [reloaded[:version], reloaded[:route], reloaded[:points][1][:name]] + end + end + + def test_a_routing_error_is_kept_with_the_points_and_tried_again_next_time + Dir.mktmpdir do |dir| + store = Maptool::TripStore.new(File.join(dir, "trip.json")) + points = [{ lngLat: [1, 2] }, { lngLat: [3, 4] }] + trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { raise Maptool::Routing::RouteError, "no route" } + assert_equal [nil, "no route", 2], [trip[:route], trip[:error], trip[:points].size] + trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { :routed } + assert_equal [:routed, nil], trip.values_at(:route, :error) + end + end +end diff --git a/test/test_updater.rb b/test/test_updater.rb new file mode 100644 index 0000000..5a380ff --- /dev/null +++ b/test/test_updater.rb @@ -0,0 +1,34 @@ +require_relative "test_helper" +require "tmpdir" +require_relative "../lib/maptool/updater" + +class UpdaterTest < Minitest::Test + def setup + Maptool::Updater.reset! + end + + def test_latest_is_mains_commit_and_its_ci_state_cached_until_checked_again + calls = [] + fetch = lambda do |url| + calls << url + url.end_with?("/branches/main") ? { "commit" => { "id" => "a" * 40 } } : { "state" => "success" } + end + assert_equal({ sha: "a" * 40, ci: "success" }, Maptool::Updater.latest("https://git", "r/m", fetch: fetch)) + assert_equal ["https://git/api/v1/repos/r/m/branches/main", "https://git/api/v1/repos/r/m/commits/#{'a' * 40}/status"], calls + Maptool::Updater.latest("https://git", "r/m", fetch: fetch) + assert_equal 2, calls.size # cached + end + + def test_gitea_out_of_reach_is_no_answer_not_an_error + assert_nil Maptool::Updater.latest("https://git", "r/m", fetch: ->(_) { raise SocketError }) + end + + def test_a_request_holds_a_full_commit_only + Dir.mktmpdir do |dir| + assert_raises(ArgumentError) { Maptool::Updater.request(dir, "abc; rm -rf /") } + Maptool::Updater.request(dir, "b" * 40) + assert_equal "b" * 40, JSON.parse(File.read(File.join(dir, "update", "request.json")))["sha"] + assert_nil Maptool::Updater.status(dir) + end + end +end diff --git a/views/importmap.erb b/views/importmap.erb index 2608a95..3e09e26 100644 --- a/views/importmap.erb +++ b/views/importmap.erb @@ -19,6 +19,7 @@ "/js/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>", "/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>", "/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>", + "/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>", "/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>", "/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>", "/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>", diff --git a/views/index.erb b/views/index.erb index 2340ddd..867ef1a 100644 --- a/views/index.erb +++ b/views/index.erb @@ -7,6 +7,7 @@ +
<% if logged_in %>