Offline routing phase 1: valhalla container building from the offline map's extracts, status in the Offline data panel
This commit is contained in:
1 parent
6f5f11cb4d
commit
bf912b96e5
13 files changed
+455
-36
No files matched your search
@@ -36,6 +36,9 @@
|
||||
/data/library.sqlite*
|
||||
/data/library/
|
||||
|
||||
# Offline routing: Valhalla tiles and its status files (lib/maptool/routing.rb)
|
||||
/data/routing/
|
||||
|
||||
# Garmin LiveTrack session IDs received via webhook
|
||||
/data/livetrack.json
|
||||
|
||||
|
||||
@@ -85,6 +85,9 @@ Deprioritized for now — revisit after the sections above land.
|
||||
=== Vanlife features
|
||||
|
||||
* [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
|
||||
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
|
||||
** [ ] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
|
||||
** [ ] Phase 3: elevation profile from terrain.pmtiles, isochrones
|
||||
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
|
||||
|
||||
=== HW integration
|
||||
|
||||
@@ -8,6 +8,7 @@ require_relative "lib/maptool/gpx"
|
||||
require_relative "lib/maptool/fit"
|
||||
require_relative "lib/maptool/gpx_store"
|
||||
require_relative "lib/maptool/library"
|
||||
require_relative "lib/maptool/routing"
|
||||
require_relative "lib/maptool/gpsd_client"
|
||||
require_relative "lib/maptool/livetrack_store"
|
||||
require_relative "lib/maptool/livetrack_client"
|
||||
@@ -142,6 +143,9 @@ module Maptool
|
||||
# this app, so a browser can't reach kiwix-serve directly by any
|
||||
# hostname/port of its own. GET /kiwix/* below proxies to it instead.
|
||||
KIWIX_URL = ENV.fetch("KIWIX_URL", "")
|
||||
# The valhalla container (docker-compose.yaml), reached server side only.
|
||||
VALHALLA_URL = ENV.fetch("VALHALLA_URL", "")
|
||||
Routing.install_service_script(DATA_DIR)
|
||||
|
||||
# Login delegates to the Gitea instance the user already has an account
|
||||
# on, rather than maintaining a local username/password — see
|
||||
@@ -417,6 +421,32 @@ module Maptool
|
||||
json PmtilesBuilder.terrain_status
|
||||
end
|
||||
|
||||
# Offline routing (lib/maptool/routing.rb): the same status/build/
|
||||
# build-status/check-update shape as the two rows above, so the Offline
|
||||
# data panel shows it the same way. Valhalla builds in its own
|
||||
# container; these only hand it requests and read its status files.
|
||||
get "/api/routing-tiles" do
|
||||
json Routing.tiles_status(DATA_DIR, VALHALLA_URL)
|
||||
end
|
||||
|
||||
get "/api/routing-tiles/check-update" do
|
||||
json update_available: Routing.update_available?(DATA_DIR)
|
||||
end
|
||||
|
||||
post "/api/routing-tiles/build" do
|
||||
require_login!
|
||||
begin
|
||||
Routing.request_build(DATA_DIR)
|
||||
rescue PmtilesBuilder::BuildError => e
|
||||
halt 409, json(error: e.message)
|
||||
end
|
||||
json status: "started"
|
||||
end
|
||||
|
||||
get "/api/routing-tiles/build-status" do
|
||||
json Routing.build_status(DATA_DIR)
|
||||
end
|
||||
|
||||
# Same reasoning as DELETE /api/offline-tiles above.
|
||||
delete "/api/terrain-tiles" do
|
||||
require_login!
|
||||
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/bin/bash
|
||||
# Runs inside the valhalla container (docker-compose.yaml), which mounts the
|
||||
# whole data/ at /data. maptool copies this script to data/routing/ at boot
|
||||
# (Maptool::Routing.install_service_script), so the container always runs
|
||||
# the version that shipped with the app. See docs/routing-design.adoc.
|
||||
#
|
||||
# Serves data/routing/tiles.tar with valhalla_service, and polls for
|
||||
# data/routing/build-request.json ({"regions": ["SK", ...]}, written by
|
||||
# maptool). A build hard-links those countries' Geofabrik extracts, builds
|
||||
# into staging/ while the old tiles keep serving, then swaps tiles.tar in
|
||||
# and restarts the service. Progress goes to status.json, the build's
|
||||
# output to build.log.
|
||||
set -u
|
||||
|
||||
R=/data/routing
|
||||
S=$R/staging
|
||||
SERVICE_PID=
|
||||
|
||||
status() { # state step [message]
|
||||
local now
|
||||
now=$(date -u +%FT%TZ)
|
||||
python3 - "$R/status.json" "$1" "$2" "${3:-}" "$now" "${STARTED:-$now}" <<'PY'
|
||||
import json, os, sys
|
||||
path, state, step, message, now, started = sys.argv[1:]
|
||||
data = {"state": state, "started_at": started}
|
||||
if step: data["step"] = step
|
||||
if state != "running": data["finished_at"] = now
|
||||
if message: data["message"] = message
|
||||
with open(path + ".tmp", "w") as f: json.dump(data, f)
|
||||
os.replace(path + ".tmp", path)
|
||||
PY
|
||||
}
|
||||
|
||||
config() { # dir
|
||||
valhalla_build_config --mjolnir-tile-dir "$1/tiles" --mjolnir-tile-extract "$1/tiles.tar" \
|
||||
--mjolnir-admin "$1/admins.sqlite" --mjolnir-concurrency "${BUILD_THREADS:-$(( $(nproc) / 2 ))}" \
|
||||
> "$1/valhalla.json"
|
||||
}
|
||||
|
||||
stop_service() {
|
||||
[ -n "$SERVICE_PID" ] || return 0
|
||||
kill "$SERVICE_PID" 2>/dev/null
|
||||
# It can take a long time to exit on SIGTERM; it holds nothing to flush.
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$SERVICE_PID" 2>/dev/null || break; sleep 0.5; done
|
||||
kill -9 "$SERVICE_PID" 2>/dev/null
|
||||
wait "$SERVICE_PID" 2>/dev/null
|
||||
SERVICE_PID=
|
||||
}
|
||||
|
||||
serve() {
|
||||
stop_service
|
||||
[ -f "$R/tiles.tar" ] || return 0
|
||||
valhalla_service "$R/valhalla.json" "${SERVICE_THREADS:-4}" &
|
||||
SERVICE_PID=$!
|
||||
}
|
||||
|
||||
build() {
|
||||
STARTED=$(date -u +%FT%TZ)
|
||||
local regions code
|
||||
rm -rf "$S" "$R/pbf"
|
||||
mkdir -p "$S" "$R/pbf"
|
||||
mv "$R/build-request.json" "$S/request.json"
|
||||
regions=$(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1]))["regions"]))' "$S/request.json")
|
||||
for code in $regions; do
|
||||
ln "/data/geofabrik_cache/$code.osm.pbf" "$R/pbf/" || { status error "" "no downloaded extract for $code"; return 1; }
|
||||
done
|
||||
: > "$R/build.log"
|
||||
run() { # step command...
|
||||
status running "$1"
|
||||
shift
|
||||
nice -n 10 "$@" >> "$R/build.log" 2>&1 || { status error "" "$(tail -c 2000 "$R/build.log")"; return 1; }
|
||||
}
|
||||
config "$S" &&
|
||||
run "admin areas" valhalla_build_admins -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
|
||||
run "routing graph ($regions)" valhalla_build_tiles -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
|
||||
run "packing tiles" valhalla_build_extract -c "$S/valhalla.json" -v || return 1
|
||||
|
||||
mv "$S/tiles.tar" "$R/tiles.tar"
|
||||
mv "$S/admins.sqlite" "$R/admins.sqlite"
|
||||
config "$R"
|
||||
mv "$S/request.json" "$R/built.json"
|
||||
rm -rf "$S" "$R/pbf"
|
||||
serve
|
||||
status done ""
|
||||
}
|
||||
|
||||
# bash as PID 1 ignores SIGTERM unless trapped: stop promptly on a redeploy.
|
||||
trap 'stop_service; exit 0' TERM INT
|
||||
|
||||
mkdir -p "$R"
|
||||
[ -f "$R/tiles.tar" ] && config "$R"
|
||||
# A build interrupted by a restart (every redeploy restarts the whole
|
||||
# compose project) starts over: its request is still in staging/.
|
||||
if [ -f "$S/request.json" ] && [ ! -f "$R/build-request.json" ]; then
|
||||
mv "$S/request.json" "$R/build-request.json"
|
||||
fi
|
||||
serve
|
||||
while true; do
|
||||
[ -f "$R/build-request.json" ] && build
|
||||
# valhalla_service died (or never started): start it again.
|
||||
if [ -n "$SERVICE_PID" ] && ! kill -0 "$SERVICE_PID" 2>/dev/null; then serve; fi
|
||||
sleep 10 & wait $! # interruptible, so the trap above runs right away
|
||||
done
|
||||
@@ -54,6 +54,8 @@ services:
|
||||
# that only forwards to maptool itself, so app.rb's GET /kiwix/*
|
||||
# proxies to this instead of handing the browser this address.
|
||||
KIWIX_URL: "http://kiwix:8080"
|
||||
# The valhalla service below, same story as KIWIX_URL.
|
||||
VALHALLA_URL: "http://valhalla:8002"
|
||||
volumes:
|
||||
# Uploaded GPX files and the offline PMTiles extract — kept outside
|
||||
# the image so a rebuild/redeploy doesn't wipe them (see
|
||||
@@ -128,6 +130,22 @@ services:
|
||||
# :z, shared for the same reason as maptool's own ./data mount above.
|
||||
- ./data/kiwix/wikipedia.zim:/data/wikipedia.zim:z
|
||||
|
||||
# Offline routing (docs/routing-design.adoc). Valhalla's own image (it
|
||||
# isn't packaged for Debian, so not in maptool's), running
|
||||
# data/routing/service.sh — bin/routing-service.sh, copied there by
|
||||
# maptool at boot so the two always match; the loop below waits for it
|
||||
# on a first start. Mounts the whole data/ (not just data/routing/) so it
|
||||
# can hard-link Geofabrik extracts from data/geofabrik_cache/ (a link
|
||||
# can't cross two bind mounts). Serves port 8002 on the compose network
|
||||
# only, maptool proxies to it.
|
||||
valhalla:
|
||||
image: ghcr.io/valhalla/valhalla:3.9.1
|
||||
restart: unless-stopped
|
||||
command: ["bash", "-c", "until [ -f /data/routing/service.sh ]; do sleep 5; done; exec bash /data/routing/service.sh"]
|
||||
volumes:
|
||||
# :z, shared for the same reason as maptool's own ./data mount above.
|
||||
- ./data:/data:z
|
||||
|
||||
networks:
|
||||
default:
|
||||
enable_ipv6: true
|
||||
@@ -58,7 +58,9 @@ expect this to flip the other way, `/srv/docker` symlinked to
|
||||
references it, and the sync step doesn't need to special-case it
|
||||
the way an earlier version of this layout did) — uploaded GPX
|
||||
files, `offline.pmtiles`, `terrain.pmtiles`, and
|
||||
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each).
|
||||
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each), and
|
||||
`routing/` (the offline routing graph, built and served by the
|
||||
`valhalla` compose service, see `docs/routing-design.adoc`).
|
||||
Persisted via that bind mount, so a redeploy never touches it.
|
||||
Also where a private import plugin belongs (`data/plugins/<name>/`,
|
||||
see `lib/maptool/plugins.rb`'s `PLUGINS_DIRS`) — `build/plugins/`
|
||||
|
||||
+76
-34
@@ -2,7 +2,7 @@
|
||||
:toc:
|
||||
:toclevels: 1
|
||||
|
||||
Status: proposal, nothing implemented yet.
|
||||
Status: *phase 1 implemented* (the container, builds, status in the Offline data panel); phases 2–3 proposed.
|
||||
|
||||
== Goal
|
||||
|
||||
@@ -12,6 +12,28 @@ extracts the offline map is built from, with the vehicle's dimensions
|
||||
under a 3 m bridge or over a 3.5 t bridge. Later on the same engine:
|
||||
an elevation profile of the route and isochrones ("how far in 2 hours").
|
||||
|
||||
== How OsmAnd and Locus do it
|
||||
|
||||
Neither routes on raw OSM. Someone else builds a compact graph once and
|
||||
the phone just downloads it:
|
||||
|
||||
* *OsmAnd*: every `.obf` map file has a routing section (roads with only
|
||||
the tags routing needs) built on OsmAnd's servers. Since 4.6 it also
|
||||
carries precomputed "HH" (highway hierarchy) shortcuts for long
|
||||
routes. Vehicle height/weight/width are profile parameters checked
|
||||
against `maxheight`/`maxweight` at query time.
|
||||
* *Locus*: offline routing goes through BRouter: `.rd5` segment files
|
||||
(5°×5° tiles, built weekly by brouter.de) and profiles scripted at
|
||||
query time. Its lookup tables have no `maxheight`/`maxweight`, so it
|
||||
can't respect vehicle dimensions. It's built for cycling first.
|
||||
|
||||
Valhalla is the same idea: the build (hours, once per map refresh)
|
||||
produces compact tiles with only roads and their restrictions (a
|
||||
fraction of the OSM extract), and queries are A* over those tiles in
|
||||
milliseconds. The difference is only that we build the tiles ourselves
|
||||
from the extracts we already have, instead of downloading someone
|
||||
else's.
|
||||
|
||||
== Engine: Valhalla
|
||||
|
||||
[cols="1,3"]
|
||||
@@ -48,43 +70,64 @@ runs.
|
||||
|
||||
== Containers
|
||||
|
||||
Valhalla isn't packaged for Debian trixie, so it doesn't go into the
|
||||
maptool image. Instead there's one more compose service, the same pattern
|
||||
as `kiwix`:
|
||||
Valhalla isn't packaged for Debian trixie, so it isn't in the maptool
|
||||
image but in its own compose service, `valhalla`, from Valhalla's image
|
||||
`ghcr.io/valhalla/valhalla` (Renovate bumps the tag). It runs
|
||||
`bin/routing-service.sh`, which maptool copies to
|
||||
`data/routing/service.sh` at boot, so the script always matches the
|
||||
deployed app. It mounts the whole `data/`, since a hard link from
|
||||
`data/geofabrik_cache/` can't cross two bind mounts.
|
||||
|
||||
[source,yaml]
|
||||
----
|
||||
valhalla:
|
||||
image: ghcr.io/valhalla/valhalla:<pinned tag> # renovate bumps it
|
||||
restart: unless-stopped
|
||||
command: ["/app/bin/routing-service.sh"]
|
||||
volumes:
|
||||
- ./data/routing:/routing:z
|
||||
- ./build/bin/routing-service.sh:/app/bin/routing-service.sh:ro,z
|
||||
----
|
||||
The two sides talk through files in `data/routing/`:
|
||||
|
||||
It uses the base image (binaries only), not `valhalla-scripted`. The
|
||||
scripted image only rebuilds when the container restarts, and maptool
|
||||
can't restart containers. Instead `bin/routing-service.sh` (~40 lines of
|
||||
shell) runs inside it:
|
||||
[cols="1,1,2"]
|
||||
|===
|
||||
| File | Written by | Meaning
|
||||
|
||||
. Serve `valhalla_service` from `tiles.tar`, if one exists.
|
||||
. Poll for `data/routing/build-request.json`. When it shows up, build
|
||||
into `staging/` (`valhalla_build_config`, `valhalla_build_admins`,
|
||||
`valhalla_build_timezones`, `valhalla_build_tiles`,
|
||||
`valhalla_build_extract`), writing the current step to `status.json`.
|
||||
. When the build succeeds, swap `staging/tiles.tar` in and restart
|
||||
`valhalla_service`. When it fails, keep the old tiles and put the log
|
||||
in `status.json`.
|
||||
| `build-request.json`
|
||||
| maptool
|
||||
| `{"regions": [...]}`: build these countries.
|
||||
|
||||
maptool reaches it at `http://valhalla:8002` (`VALHALLA_URL`), server
|
||||
side only, like `KIWIX_URL`.
|
||||
| `status.json`
|
||||
| container
|
||||
| `state` (running/done/error), `step`, `started_at`, `message`.
|
||||
|
||||
| `tiles.tar`, `admins.sqlite`, `valhalla.json`
|
||||
| container
|
||||
| The served graph.
|
||||
|
||||
| `built.json`
|
||||
| container
|
||||
| The request the current tiles were built from.
|
||||
|
||||
| `build.log`
|
||||
| container
|
||||
| The last build's output.
|
||||
|===
|
||||
|
||||
The script serves `tiles.tar` with `valhalla_service`, polls for a
|
||||
request every 10 s, and builds into `staging/` while the old tiles keep
|
||||
serving. It runs `valhalla_build_admins`, then `valhalla_build_tiles`,
|
||||
then `valhalla_build_extract`, at `nice 10` with half the cores. When
|
||||
the build succeeds, it swaps the tiles in and restarts the service. A
|
||||
failure keeps the old tiles and puts the end of the log in
|
||||
`status.json`. Every redeploy restarts the whole compose project; a
|
||||
build cut off that way starts over on its own (its request is still in
|
||||
`staging/`).
|
||||
|
||||
No timezone database (`valhalla_build_timezones` downloads one): only
|
||||
time-dependent routing needs it.
|
||||
|
||||
Tested locally with Liechtenstein: the build takes 2 s, a rebuild while
|
||||
serving swaps the tiles in, and a truck route with dimensions comes back.
|
||||
|
||||
== maptool side
|
||||
|
||||
* "Build routing" next to the existing offline/terrain builds, login
|
||||
required. It writes `build-request.json` and links the PBF files.
|
||||
Status and history appear in the same build panel (`build_history`).
|
||||
* "Offline routing" row in the Offline data panel, next to the offline
|
||||
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
|
||||
three. A routing request made while the offline map is still
|
||||
downloading extracts waits for it (`Routing.offline_build_finished`).
|
||||
The row says whether the service answers.
|
||||
* `POST /api/route` proxies to Valhalla `/route` with `costing: truck`
|
||||
and the vehicle profile filled in. It's open to everyone, like the
|
||||
map. Login is required only to save the result.
|
||||
@@ -107,7 +150,6 @@ side only, like `KIWIX_URL`.
|
||||
|
||||
== Open questions
|
||||
|
||||
* Pin a Valhalla version: take the latest `ghcr.io/valhalla/valhalla`
|
||||
release tag at implementation time and add it to Renovate (a docker
|
||||
image in compose is tracked by default).
|
||||
* Trailer / several vehicle profiles: one profile until it's needed.
|
||||
* Build time and size for all 14 countries: measure on the first build
|
||||
on the server.
|
||||
@@ -145,6 +145,11 @@ similar); see
|
||||
https://download.mapterhorn.com/attribution.json[their own attribution
|
||||
list] for the full provenance.
|
||||
|
||||
Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
|
||||
(MIT) in its own container from Valhalla's published image
|
||||
(`ghcr.io/valhalla/valhalla`, version pinned in `docker-compose.yaml`),
|
||||
over the same Geofabrik extracts (ODbL). See `docs/routing-design.adoc`.
|
||||
|
||||
Not a frontend asset like the above, but also baked into this app's own
|
||||
Docker image (not a separate container the way kiwix-serve/gpsd are —
|
||||
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
|
||||
|
||||
@@ -245,6 +245,8 @@ module Maptool
|
||||
run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
|
||||
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
|
||||
end
|
||||
# A routing build requested meanwhile waited for these extracts.
|
||||
Routing.offline_build_finished(data_dir) if defined?(Routing)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
require "fileutils"
|
||||
require "json"
|
||||
require "net/http"
|
||||
require "time"
|
||||
require_relative "pmtiles_builder"
|
||||
|
||||
module Maptool
|
||||
# maptool's side of offline routing (docs/routing-design.adoc). Valhalla
|
||||
# runs in its own container (bin/routing-service.sh); the two talk
|
||||
# through files in data/routing/: maptool writes build-request.json, the
|
||||
# container writes status.json, built.json and tiles.tar.
|
||||
module Routing
|
||||
SERVICE_SCRIPT = File.expand_path("../../bin/routing-service.sh", __dir__)
|
||||
MUTEX = Mutex.new
|
||||
@pending = false
|
||||
|
||||
def self.dir(data_dir)
|
||||
File.join(data_dir, "routing")
|
||||
end
|
||||
|
||||
def self.tiles_path(data_dir)
|
||||
File.join(dir(data_dir), "tiles.tar")
|
||||
end
|
||||
|
||||
# At boot: the container runs whatever script is in data/routing/, so it
|
||||
# always matches the deployed app.
|
||||
def self.install_service_script(data_dir)
|
||||
FileUtils.mkdir_p(dir(data_dir))
|
||||
FileUtils.cp(SERVICE_SCRIPT, File.join(dir(data_dir), "service.sh"))
|
||||
end
|
||||
|
||||
# Routing covers the offline map's selected countries. While an offline
|
||||
# build is running (it may be downloading those very extracts), the
|
||||
# request waits for it — PmtilesBuilder calls offline_build_finished.
|
||||
def self.request_build(data_dir)
|
||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
|
||||
|
||||
MUTEX.synchronize do
|
||||
if PmtilesBuilder.offline_status[:state] == "running"
|
||||
@pending = true
|
||||
return
|
||||
end
|
||||
missing = codes.reject { |code| File.exist?(extract_path(data_dir, code)) }
|
||||
raise PmtilesBuilder::BuildError, "no downloaded map data for #{missing.join(", ")}, build the offline map first" if missing.any?
|
||||
|
||||
write_json(File.join(dir(data_dir), "build-request.json"), regions: codes, requested_at: Time.now.utc.iso8601)
|
||||
end
|
||||
end
|
||||
|
||||
def self.offline_build_finished(data_dir)
|
||||
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
|
||||
request_build(data_dir) if pending
|
||||
rescue PmtilesBuilder::BuildError
|
||||
nil # the offline build failed to download something; its own row shows that
|
||||
end
|
||||
|
||||
# The DataFileRow build-status shape (offline_data.js): state, step,
|
||||
# started_at, message.
|
||||
def self.build_status(data_dir)
|
||||
return { state: "running", step: "waiting for the offline map build" } if MUTEX.synchronize { @pending }
|
||||
return { state: "running", step: "waiting for the routing container" } if File.exist?(File.join(dir(data_dir), "build-request.json"))
|
||||
|
||||
read_json(File.join(dir(data_dir), "status.json")) || { state: "idle" }
|
||||
end
|
||||
|
||||
# The DataFileRow status shape, plus whether Valhalla answers.
|
||||
def self.tiles_status(data_dir, valhalla_url)
|
||||
path = tiles_path(data_dir)
|
||||
return { available: false } unless File.exist?(path)
|
||||
|
||||
built = read_json(File.join(dir(data_dir), "built.json")) || {}
|
||||
{ available: true, size: File.size(path), mtime: File.mtime(path).utc.iso8601,
|
||||
meta: { sources: (built[:regions] || []).map { |code| { code: code } }, serving: serving?(valhalla_url) } }
|
||||
end
|
||||
|
||||
# nil = never built, true = other countries selected or a newer
|
||||
# extract downloaded since, false = up to date.
|
||||
def self.update_available?(data_dir)
|
||||
path = tiles_path(data_dir)
|
||||
return nil unless File.exist?(path)
|
||||
|
||||
built = (read_json(File.join(dir(data_dir), "built.json")) || {})[:regions] || []
|
||||
codes = PmtilesBuilder.selected_regions(data_dir)
|
||||
return true unless built.sort == codes.sort
|
||||
|
||||
codes.any? { |code| File.exist?(extract_path(data_dir, code)) && File.mtime(extract_path(data_dir, code)) > File.mtime(path) }
|
||||
end
|
||||
|
||||
def self.serving?(valhalla_url)
|
||||
return false if valhalla_url.to_s.empty?
|
||||
|
||||
uri = URI("#{valhalla_url}/status")
|
||||
Net::HTTP.start(uri.host, uri.port, open_timeout: 1, read_timeout: 2) { |http| http.get(uri.path).is_a?(Net::HTTPSuccess) }
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
|
||||
def self.extract_path(data_dir, code)
|
||||
File.join(data_dir, "geofabrik_cache", "#{code}.osm.pbf")
|
||||
end
|
||||
private_class_method :extract_path
|
||||
|
||||
def self.read_json(path)
|
||||
JSON.parse(File.read(path), symbolize_names: true)
|
||||
rescue Errno::ENOENT, JSON::ParserError
|
||||
nil
|
||||
end
|
||||
private_class_method :read_json
|
||||
|
||||
def self.write_json(path, data)
|
||||
File.write("#{path}.tmp", JSON.generate(data))
|
||||
File.rename("#{path}.tmp", path)
|
||||
end
|
||||
private_class_method :write_json
|
||||
|
||||
def self.reset!
|
||||
MUTEX.synchronize { @pending = false }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -48,6 +48,13 @@ function formatOfflineMeta(meta) {
|
||||
return ` · ${meta.sources.map((s) => s.code).join(", ")}`;
|
||||
}
|
||||
|
||||
// Routing tiles live in the valhalla container's hands (see
|
||||
// lib/maptool/routing.rb); "serving" says whether it actually answers.
|
||||
function formatRoutingMeta(meta) {
|
||||
if (!meta) return "";
|
||||
return `${formatOfflineMeta(meta)} · ${meta.serving ? "routing ready" : "routing service not running"}`;
|
||||
}
|
||||
|
||||
function formatTerrainMeta(meta) {
|
||||
if (!meta) return "";
|
||||
const count = meta.sources.length;
|
||||
@@ -204,6 +211,18 @@ class DataFileRow {
|
||||
this._deleteButton.addEventListener("click", () => this._delete());
|
||||
container.appendChild(row);
|
||||
this._refreshStatus();
|
||||
this._resumePolling();
|
||||
}
|
||||
|
||||
// A build started earlier (a routing build runs for hours) keeps showing
|
||||
// its progress after a page reload.
|
||||
async _resumePolling() {
|
||||
try {
|
||||
const status = await (await fetch(this._buildStatusUrl)).json();
|
||||
if (status.state === "running") this._poll();
|
||||
} catch {
|
||||
// status stays whatever _refreshStatus shows
|
||||
}
|
||||
}
|
||||
|
||||
// Single place that writes to _statusEl, so the error styling (pre-wrap,
|
||||
@@ -231,7 +250,7 @@ class DataFileRow {
|
||||
|
||||
const updated = new Date(data.mtime).toLocaleString([], { dateStyle: "short", timeStyle: "short" });
|
||||
this._setStatus(`${formatBytes(data.size)} · updated ${updated}${this._formatMeta(data.meta)}`);
|
||||
this._deleteButton.hidden = !isLoggedIn();
|
||||
this._deleteButton.hidden = !isLoggedIn() || !this._deleteUrl;
|
||||
this._checkUpdate();
|
||||
}
|
||||
|
||||
@@ -368,6 +387,15 @@ export class OfflineDataControl {
|
||||
checkUpdateUrl: "/api/terrain-tiles/check-update",
|
||||
formatMeta: formatTerrainMeta,
|
||||
}),
|
||||
// No delete: the tiles are in use by the routing container.
|
||||
new DataFileRow({
|
||||
label: "Offline routing",
|
||||
statusUrl: "/api/routing-tiles",
|
||||
buildUrl: "/api/routing-tiles/build",
|
||||
buildStatusUrl: "/api/routing-tiles/build-status",
|
||||
checkUpdateUrl: "/api/routing-tiles/check-update",
|
||||
formatMeta: formatRoutingMeta,
|
||||
}),
|
||||
];
|
||||
this._regionPicker = new RegionPicker(() => this._rows.forEach((row) => row.triggerBuild()));
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ module AppTestHelper
|
||||
File.write(File.join(Maptool::App::DATA_DIR, "livetrack.json"), "[]")
|
||||
FileUtils.rm_f(File.join(Maptool::App::DATA_DIR, "offline_regions.json"))
|
||||
Maptool::PmtilesBuilder.reset!
|
||||
Maptool::Routing.reset!
|
||||
super
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/routing"
|
||||
|
||||
class RoutingTest < Minitest::Test
|
||||
def setup
|
||||
@data = Dir.mktmpdir
|
||||
@routing = File.join(@data, "routing")
|
||||
FileUtils.mkdir_p([@routing, File.join(@data, "geofabrik_cache")])
|
||||
Maptool::PmtilesBuilder.set_selected_regions(@data, %w[SK])
|
||||
end
|
||||
|
||||
def teardown
|
||||
FileUtils.remove_entry(@data)
|
||||
Maptool::PmtilesBuilder.reset!
|
||||
Maptool::Routing.reset!
|
||||
end
|
||||
|
||||
def test_a_build_needs_the_extracts_and_writes_a_request_for_the_container
|
||||
assert_raises(Maptool::PmtilesBuilder::BuildError) { Maptool::Routing.request_build(@data) }
|
||||
|
||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||
Maptool::Routing.request_build(@data)
|
||||
assert_equal %w[SK], JSON.parse(File.read(File.join(@routing, "build-request.json")))["regions"]
|
||||
assert_equal "waiting for the routing container", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
|
||||
def test_a_request_during_an_offline_build_waits_for_it
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "running")
|
||||
Maptool::Routing.request_build(@data)
|
||||
assert_equal "waiting for the offline map build", Maptool::Routing.build_status(@data)[:step]
|
||||
refute File.exist?(File.join(@routing, "build-request.json"))
|
||||
|
||||
Maptool::PmtilesBuilder::OFFLINE_STATUS.replace(state: "done")
|
||||
File.write(File.join(@data, "geofabrik_cache", "SK.osm.pbf"), "pbf")
|
||||
Maptool::Routing.offline_build_finished(@data)
|
||||
assert File.exist?(File.join(@routing, "build-request.json"))
|
||||
end
|
||||
|
||||
def test_update_check_compares_regions_and_extract_age
|
||||
assert_nil Maptool::Routing.update_available?(@data)
|
||||
|
||||
pbf = File.join(@data, "geofabrik_cache", "SK.osm.pbf")
|
||||
File.write(pbf, "pbf")
|
||||
File.utime(Time.now - 60, Time.now - 60, pbf)
|
||||
File.write(File.join(@routing, "tiles.tar"), "tiles")
|
||||
File.write(File.join(@routing, "built.json"), JSON.generate(regions: %w[SK]))
|
||||
refute Maptool::Routing.update_available?(@data)
|
||||
|
||||
File.utime(Time.now + 60, Time.now + 60, pbf)
|
||||
assert Maptool::Routing.update_available?(@data)
|
||||
Maptool::PmtilesBuilder.set_selected_regions(@data, %w[SK CZ])
|
||||
assert Maptool::Routing.update_available?(@data)
|
||||
assert_equal [{ code: "SK" }], Maptool::Routing.tiles_status(@data, "")[:meta][:sources]
|
||||
end
|
||||
|
||||
def test_the_container_status_file_is_passed_through
|
||||
assert_equal({ state: "idle" }, Maptool::Routing.build_status(@data))
|
||||
File.write(File.join(@routing, "status.json"), JSON.generate(state: "running", step: "packing tiles"))
|
||||
assert_equal "packing tiles", Maptool::Routing.build_status(@data)[:step]
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user