Files
maptool/lib/maptool/routing.rb
T
2026-11-14 21:20:23 +01:00

338 lines
15 KiB
Ruby

require "fileutils"
require "json"
require "net/http"
require "open3"
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
@merging = nil # status while osmium merges the extracts, then nil (or the error)
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 its downloads — PmtilesBuilder calls extracts_ready.
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.fetching_extracts?
@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?
# Apply again while the same countries are building: nothing to queue.
running = read_json(File.join(dir(data_dir), "staging", "request.json"))
return if running && running[:regions] == codes && running.key?(:pbf) == (codes.size > 1) && read_json(File.join(dir(data_dir), "status.json"))&.dig(:state) == "running"
return if @merging&.dig(:state) == "running"
@merging = nil
if codes.size == 1
write_request(data_dir, codes, nil)
else
@merging = { state: "running", step: "merging extracts with osmium", started_at: Time.now.utc.iso8601 }
Thread.new { merge_and_request(data_dir, codes) }
end
end
end
# Valhalla breaks on several overlapping country extracts (border ways
# in each: "Failed tile ... _M_range_check", valhalla#3925), so it gets
# one merged file. Its image has no osmium; this container does.
def self.merge_and_request(data_dir, codes)
merged = File.join(dir(data_dir), "merged.osm.pbf")
part = File.join(dir(data_dir), "merged.part.osm.pbf") # osmium picks the format by extension
inputs = codes.map { |code| extract_path(data_dir, code) }
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", part)
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
File.rename(part, merged)
MUTEX.synchronize do
write_request(data_dir, codes, "routing/merged.osm.pbf")
@merging = nil
end
rescue StandardError => e
FileUtils.rm_f(part)
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
end
private_class_method :merge_and_request
# pbf: the file to build from, relative to data/ (nil: the one extract).
def self.write_request(data_dir, codes, pbf)
write_json(File.join(dir(data_dir), "build-request.json"), { regions: codes, pbf: pbf, requested_at: Time.now.utc.iso8601 }.compact)
end
private_class_method :write_request
def self.extracts_ready(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)
pending, merging = MUTEX.synchronize { [@pending, @merging] }
return { state: "running", step: "waiting for the offline map downloads" } if pending
return merging if merging
status = read_json(File.join(dir(data_dir), "status.json"))
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
return { state: "running", step: "waiting for the routing container" } if File.exist?(File.join(dir(data_dir), "build-request.json"))
status || { 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
class RouteError < StandardError; end
class Unavailable < StandardError; end
# A camper by default; one profile for now (docs/routing-design.adoc).
# Vehicle profiles: a name plus optional limits (nil: no limit, a plain
# car). Stored for everyone, picked per browser (route.js).
DEFAULT_VEHICLES = [
{ id: "car", name: "Car" },
{ id: "camper", name: "Camper", height: 3.0, width: 2.3, length: 7.0, weight: 3.5 },
].freeze
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60 }.freeze
# Up to this weight Valhalla's "auto" costing (with height/width) fits
# better than "truck": a camper isn't kept off roads closed to lorries.
CAR_MAX_WEIGHT = 3.5
def self.vehicles(data_dir)
read_json(File.join(data_dir, "vehicles.json")) || begin
# The single vehicle stored before profiles became the camper.
old = read_json(File.join(data_dir, "vehicle.json"))
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(*VEHICLE_LIMITS.keys))] : DEFAULT_VEHICLES
end
end
# The profile with this id, or the first one.
def self.vehicle(data_dir, id = nil)
list = vehicles(data_dir)
list.find { |v| v[:id] == id } || list.first
end
# Replaces the whole list: [{ "id", "name", "height", ... }, ...].
def self.save_vehicles(data_dir, list)
raise ArgumentError, "at least one vehicle is needed" unless list.is_a?(Array) && list.any? && list.size <= 20
vehicles = list.map do |values|
raise ArgumentError, "invalid vehicle" unless values.is_a?(Hash)
name = values["name"].to_s.strip
id = values["id"].to_s
raise ArgumentError, "every vehicle needs a name" if name.empty? || name.size > 40
raise ArgumentError, "invalid vehicle id" unless id.match?(/\A[\w-]{1,40}\z/)
limits = VEHICLE_LIMITS.to_h do |key, range|
raw = values[key.to_s]
next [key, nil] if raw.nil? || raw.to_s.strip.empty?
value = Float(raw, exception: false)
raise ArgumentError, "#{name}: #{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
[key, value]
end
{ id: id, name: name, **limits.compact }
end
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
write_json(File.join(data_dir, "vehicles.json"), vehicles)
vehicles
end
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
# (km), time (s), the turn-by-turn instructions and, per country, the
# km on motorways and toll roads (for vignettes and tolls).
# avoid: {"tolls" => true, "highways" => true}, for the whole route.
def self.route(valhalla_url, locations, vehicle, avoid = {})
raise RouteError, "at least two points are needed" if locations.size < 2
costing, options = costing(vehicle, avoid)
data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers")
legs = data["trip"]["legs"]
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"],
countries: countries(valhalla_url, legs, costing, options),
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
def self.countries(valhalla_url, legs, costing, options)
totals = {}
legs.each do |leg|
data = valhalla(valhalla_url, "/trace_attributes",
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
costing_options: { costing => options },
filters: { attributes: %w[edge.length edge.road_class edge.toll node.admin_index admin.country_code], action: "include" })
codes = data["admins"].map { |admin| admin["country_code"] }
data["edges"].each do |edge|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
row = totals[code] ||= { code: code, km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
row[:km] += edge["length"]
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
row[:toll_km] += edge["length"] if edge["toll"]
end
end
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
nil
end
private_class_method :countries
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
# GeoJSON FeatureCollection of polygons, largest first.
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
lon, lat = center
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
costing, options = costing(vehicle, avoid)
valhalla(valhalla_url, "/isochrone",
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
contours: minutes.map { |m| { time: m } }, polygons: true)
rescue ArgumentError, TypeError
raise RouteError, "invalid center or times"
end
# Up to CAR_MAX_WEIGHT "auto" with height/width, above it "truck".
def self.costing(vehicle, avoid = {})
limits = vehicle.slice(*VEHICLE_LIMITS.keys).compact
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
avoid = {} unless avoid.is_a?(Hash)
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
options = options.merge(use_highways: 0.0) if avoid["highways"]
[costing, options]
end
private_class_method :costing
def self.valhalla(valhalla_url, path, body)
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
uri = URI("#{valhalla_url}#{path}")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no result" unless response.is_a?(Net::HTTPSuccess)
data
end
private_class_method :valhalla
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
def self.decode_polyline(encoded)
values = []
value = shift = 0
encoded.each_byte do |byte|
byte -= 63
value |= (byte & 0x1f) << shift
shift += 5
next if byte >= 0x20
values << ((value & 1).zero? ? value >> 1 : ~(value >> 1))
value = shift = 0
end
lat = lon = 0
values.each_slice(2).map do |dlat, dlon|
lat += dlat
lon += dlon
[lon / 1e6, lat / 1e6]
end
end
def self.reset!
MUTEX.synchronize { @pending = false; @merging = nil }
end
end
end