From bd689faa9371fcc42889a2bddf7bbe6463a58f21 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Tue, 1 Dec 2026 10:14:57 +0100 Subject: [PATCH] Trip log crash-safe like a FIT: an append-only journal per trip (data/trip_log/.ndjson, fsynced every 5 s, a torn last line skipped and the next one on a line of its own), a restart picks the running trip up from it into the same track, no state file to corrupt; the library's track built from it every 5 min and at the end. Drive mode: a pinned side panel's room goes back to the map --- TODO.adoc | 5 +- app.rb | 2 +- lib/maptool/trip_log.rb | 153 +++++++++++++++++++++++++++------------- public/css/style.css | 3 + test/test_trip_log.rb | 53 +++++++++++--- 5 files changed, 154 insertions(+), 62 deletions(-) diff --git a/TODO.adoc b/TODO.adoc index 3cb5059..f47ca89 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -123,7 +123,10 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod the folder's `icon` — by hand (the notes' icon picker, POI_ICONS / NPS) or, unset, from its points (the destination's, else the most common) Done: `lib/maptool/trip_log.rb`, `GET/POST/DELETE /api/trip/log`, the Trip menu's - Start / End, the line really driven (`--route-driven`). Still to do: the pictogram, the + Start / End, the line really driven (`--route-driven`). Stored crash-safe like a FIT: an + append-only journal per trip (`data/trip_log/.ndjson`, fsynced every 5 s, a torn + last line skipped), a restart picks the running trip up from it; the library's track built + from it every 5 min and at the end. Still to do: the pictogram, the planned route dashed behind, a walk from another device shown with it, visited points ** [ ] Colors: planned vs really driven — the planned route (magenta ahead, the part behind thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc diff --git a/app.rb b/app.rb index 1c24346..65d0a54 100644 --- a/app.rb +++ b/app.rb @@ -747,7 +747,7 @@ module Maptool # the line's coordinates from N on), POST {"name"} starts it — a # Trips/ folder with the planned route and its stops — # DELETE ends it. Every fix goes in meanwhile (App.gnss_update). - TRIP_LOG = TripLog.new(File.join(DATA_DIR, "trip_log.json"), library: LIBRARY) + TRIP_LOG = TripLog.new(File.join(DATA_DIR, "trip_log"), library: LIBRARY) get "/api/trip/log" do require_login! diff --git a/lib/maptool/trip_log.rb b/lib/maptool/trip_log.rb index 90cd207..4945877 100644 --- a/lib/maptool/trip_log.rb +++ b/lib/maptool/trip_log.rb @@ -1,5 +1,6 @@ require "json" require "time" +require "fileutils" require_relative "track_stats" require_relative "gnss_sim" @@ -8,37 +9,43 @@ module Maptool # a trip is a library folder, Trips/ . Start makes it — with # the planned route and its named stops in it — and from then on every # GNSS fix (App.gnss_update) that moved MIN_STEP_M goes into the car's - # track there, written into the library every FLUSH_EVERY_S (a power cut - # loses that much at most) and at the end. A walk away from the car comes - # from another device's track put into the same folder (a FIT, LiveTrack). + # track there. + # + # Crash-safe like a FIT file, by being append-only: each point is a line + # appended to the trip's journal (/.ndjson), fsynced + # every FSYNC_EVERY_S — a power cut loses those few seconds at most, a + # torn last line is skipped. The journal's first line says which trip it + # is, a line names the library track once made, the last one ends it; so + # a restart (or a lost state file) picks the running trip up again from + # the newest journal with no end. The library's track is built from it + # every LIBRARY_EVERY_S and at the end (each build rewrites it — the + # journal is what's kept per point). class TripLog MIN_STEP_M = 10 - FLUSH_EVERY_S = 60 + FSYNC_EVERY_S = 5 + LIBRARY_EVERY_S = 300 ROOT = "Trips".freeze - def initialize(path, library:) - @path = path + def initialize(dir, library:) + @dir = dir @library = library @mutex = Mutex.new - @state = begin - JSON.parse(File.read(path), symbolize_names: true) - rescue Errno::ENOENT, JSON::ParserError - {} - end - @flushed_at = 0 + FileUtils.mkdir_p(dir) + @trip = resume + @synced_at = @built_at = 0 end def active? - @mutex.synchronize { !!@state[:folder] } + @mutex.synchronize { !!@trip } end # { active:, folder:, started_at:, points:, distance_m: } — coordinates # from index `since` on with `since:` (the map draws the line as it grows). def status(since: nil) @mutex.synchronize do - points = @state[:points] || [] - result = { active: !!@state[:folder], folder: @state[:folder], started_at: @state[:started_at], points: points.size, - distance_m: TrackStats.compute(points.map { |p| p.first(3) })["distance_meters"] } + points = @trip ? @trip[:points] : [] + result = { active: !!@trip, folder: @trip&.dig(:folder), started_at: @trip&.dig(:started_at), points: points.size, + distance_m: TrackStats.compute(points.map { |p| p.first(2) })["distance_meters"] } result[:coordinates] = points[since.to_i..].to_a.map { |p| p.first(2) } if since result end @@ -48,7 +55,7 @@ module Maptool # folder as a route and points. Returns the folder. def start(name, plan: nil, stops: [], now: Time.now) @mutex.synchronize do - raise ArgumentError, "a trip is already running (#{@state[:folder]})" if @state[:folder] + raise ArgumentError, "a trip is already running (#{@trip[:folder]})" if @trip folder = "#{ROOT}/#{[now.strftime('%Y-%m-%d'), name.to_s.strip].reject(&:empty?).join(' ')}" @library.create_folder(folder) @@ -62,8 +69,11 @@ module Maptool features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } } end @library.import_features(features, folder: folder) unless features.empty? - @state = { folder: folder, started_at: now.to_i, points: [], item: nil } - save + started = now.to_i + @trip = { folder: folder, started_at: started, points: [], item: nil, path: File.join(@dir, "#{started}.ndjson") } + journal(trip: folder, started_at: started) + sync + File.open(@dir, &:fsync) # the new journal's name on disk too folder end end @@ -71,54 +81,99 @@ module Maptool # A fix: [lon, lat], altitude (m, or nil), at (epoch seconds). def record(lon, lat, alt, at) @mutex.synchronize do - return unless @state[:folder] + return unless @trip - last = @state[:points].last + last = @trip[:points].last return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M - @state[:points] << [lon, lat, alt, at.to_f.round(1)] - flush if at.to_f - @flushed_at >= FLUSH_EVERY_S + point = [lon, lat, alt, at.to_f.round(1)] + @trip[:points] << point + journal(point) + now = Process.clock_gettime(Process::CLOCK_MONOTONIC) + if now - @synced_at >= FSYNC_EVERY_S + sync + @synced_at = now + end + if now - @built_at >= LIBRARY_EVERY_S + build + @built_at = now + end end end - # Ends it: the track written a last time. Returns the folder. + # Ends it: the track built a last time, the journal closed. Returns the folder. def stop @mutex.synchronize do - folder = @state[:folder] or return nil - flush - @state = {} - save + return nil unless @trip + + build + journal(end: Time.now.to_i) + sync + @file&.close + @file = nil + folder = @trip[:folder] + @trip = nil folder end end private - # The car's track into the library (made on the first flush, replaced - # after), the state file with it. - def flush - points = @state[:points] - if points.size >= 2 - coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } - times = points.map { |p| Time.at(p[3]) } - name = "Car #{Time.at(@state[:started_at]).strftime('%Y-%m-%d %H:%M')}" - feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates }, - "properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" } - .merge(TrackStats.compute(coordinates, times: times)) - .merge("profile" => TrackStats.build_profile(coordinates, times: times)) } - if @state[:item] - @library.update_feature(@state[:item], @state[:item].delete_prefix("item:"), feature) - else - @state[:item] = @library.import_features([feature], folder: @state[:folder]).find { |key| key.start_with?("item:") } + # The newest journal with no end: the trip still running. + def resume + Dir[File.join(@dir, "*.ndjson")].max_by { |path| File.basename(path, ".ndjson").to_i }&.then do |path| + trip = nil + File.foreach(path) do |line| + entry = JSON.parse(line) rescue next # a line torn by a power cut + case entry + when Array then trip&.dig(:points)&.push(entry) + when Hash + trip = { folder: entry["trip"], started_at: entry["started_at"], points: [], item: nil, path: path } if entry["trip"] + trip[:item] = entry["item"] if trip && entry["item"] + trip = nil if entry["end"] + end end + trip end - @flushed_at = points.last ? points.last[3] : 0 - save end - def save - File.write("#{@path}.tmp", JSON.generate(@state)) - File.rename("#{@path}.tmp", @path) + def journal(entry) + unless @file + @file = File.open(@trip[:path], "a+") + # a line torn by a power cut: the next one starts on a line of its own + if @file.size.positive? + @file.seek(-1, IO::SEEK_END) + @file.write("\n") unless @file.read(1) == "\n" + end + end + @file.puts(JSON.generate(entry)) + end + + def sync + @file&.flush + @file&.fsync + end + + # The car's track into the library from the points so far (made on the + # first build, its key journaled, replaced after). + def build + points = @trip[:points] + return if points.size < 2 + + coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } + times = points.map { |p| Time.at(p[3]) } + name = "Car #{Time.at(@trip[:started_at]).strftime('%Y-%m-%d %H:%M')}" + feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates }, + "properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" } + .merge(TrackStats.compute(coordinates, times: times)) + .merge("profile" => TrackStats.build_profile(coordinates, times: times)) } + if @trip[:item] + @library.update_feature(@trip[:item], @trip[:item].delete_prefix("item:"), feature) + else + @trip[:item] = @library.import_features([feature], folder: @trip[:folder]).find { |key| key.start_with?("item:") } + journal(item: @trip[:item]) + sync + end end end end diff --git a/public/css/style.css b/public/css/style.css index 2d7ffdd..fe12361 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3529,6 +3529,9 @@ button.basemap-panel__link[hidden] { display: none; } cursor: pointer; } .topbar__drive.active { background: var(--accent); border-color: var(--accent); color: #fff; } +/* a panel pinned open stays hidden while driving: its room goes back to + the map (the panel and its room come back on leaving) */ +html.driving body.side-pinned #map { margin-left: 0 !important; } /* outranks the :has() rule above */ html.driving #sidebar, html.driving .basemap-panel, html.driving .gpx-panel, diff --git a/test/test_trip_log.rb b/test/test_trip_log.rb index cf64cbe..fd9ccd8 100644 --- a/test/test_trip_log.rb +++ b/test/test_trip_log.rb @@ -5,13 +5,20 @@ require "maptool/gpx_store" require "maptool/trip_log" class TripLogTest < Minitest::Test + def library(dir) + Maptool::Library.new(File.join(dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(dir, "gpx")), sources_dir: File.join(dir, "sources")) + end + + def names(library) + library.nodes.flat_map { |label, _key, _stamp, read| [label, *JSON.parse(read.call)["features"].map { |f| f.dig("properties", "name") }] }.compact.join(" ") + end + # Start makes the folder with the plan and its named stops; fixes 10 m - # apart become the car's track (written on the first flush, replaced - # after); stop closes it. + # apart become the car's track; stop builds it into the library. def test_a_trip_records_into_its_folder Dir.mktmpdir do |dir| - library = Maptool::Library.new(File.join(dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(dir, "gpx")), sources_dir: File.join(dir, "sources")) - log = Maptool::TripLog.new(File.join(dir, "trip_log.json"), library: library) + lib = library(dir) + log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: lib) plan = { geometry: { type: "LineString", coordinates: [[17.0, 48.0], [17.1, 48.0]] }, properties: { distance_km: 7.4, time_s: 600 } } folder = log.start("Tatry", plan: plan, stops: [{ lngLat: [17.0, 48.0], name: "My position" }, { lngLat: [17.1, 48.0], name: "Camp" }], now: Time.utc(2026, 12, 1, 8)) assert_equal "Trips/2026-12-01 Tatry", folder @@ -20,18 +27,42 @@ class TripLogTest < Minitest::Test log.record(17.0, 48.0, 150, 1000) log.record(17.00001, 48.0, 150, 1001) # < 10 m: skipped log.record(17.001, 48.0, 151, 1002) - log.record(17.002, 48.0, 152, 1100) # a minute on: flushed + log.record(17.002, 48.0, 152, 1100) assert_equal 3, log.status[:points] assert_equal [[17.001, 48.0], [17.002, 48.0]], log.status(since: 1)[:coordinates] assert_equal folder, log.stop refute log.active? - names = library.nodes.flat_map { |label, _key, _stamp, read| [label, *JSON.parse(read.call)["features"].map { |f| f.dig("properties", "name") }] }.compact - assert(library.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder - assert_includes names.join(" "), "Camp" - assert_includes names.join(" "), "Car 2026-12-01" - assert_includes names.join(" "), "Plan" - refute_includes names.join(" "), "My position" + all = names(lib) + %w[Camp Plan].each { |name| assert_includes all, name } + assert_includes all, "Car 2026-12-01" + refute_includes all, "My position" + assert(lib.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder + end + end + + # A crash: the server restarts with the journal as it was — a torn last + # line included — and the trip goes on from there, into the same track. + def test_a_restart_picks_the_trip_up_from_its_journal + Dir.mktmpdir do |dir| + lib = library(dir) + log_dir = File.join(dir, "trip_log") + log = Maptool::TripLog.new(log_dir, library: lib) + log.start("Crash", now: Time.utc(2026, 12, 1, 8)) + log.record(17.0, 48.0, nil, 1000) + log.record(17.001, 48.0, nil, 1010) + log.send(:sync) # as the FSYNC_EVERY_S timer does; what's after it is lost in a crash + journal = Dir[File.join(log_dir, "*.ndjson")].first + File.open(journal, "a") { |f| f.write("[17.00") } # the power cut, mid-line + + again = Maptool::TripLog.new(log_dir, library: lib) + assert again.active? + assert_equal [2, "Trips/2026-12-01 Crash"], again.status.values_at(:points, :folder) + again.record(17.002, 48.0, nil, 1020) + again.stop + assert_equal 3, File.readlines(journal).count { |l| l.start_with?("[") && (JSON.parse(l) rescue nil) } # the torn line alone lost + assert_equal 1, lib.nodes.count { |label, *| label.include?("Car 2026-12-01") } # one track, not two + refute Maptool::TripLog.new(log_dir, library: lib).active? # ended stays ended end end end