Trip log crash-safe like a FIT: an append-only journal per trip (data/trip_log/<started>.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
This commit is contained in:
1 parent
0c809b3e2b
commit
bd689faa93
5 files changed
+150
-58
No files matched your search
@@ -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
|
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)
|
points (the destination's, else the most common)
|
||||||
Done: `lib/maptool/trip_log.rb`, `GET/POST/DELETE /api/trip/log`, the Trip menu's
|
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/<started>.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
|
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
|
** [ ] 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
|
thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc
|
||||||
|
|||||||
@@ -747,7 +747,7 @@ module Maptool
|
|||||||
# the line's coordinates from N on), POST {"name"} starts it — a
|
# the line's coordinates from N on), POST {"name"} starts it — a
|
||||||
# Trips/<date> <name> folder with the planned route and its stops —
|
# Trips/<date> <name> folder with the planned route and its stops —
|
||||||
# DELETE ends it. Every fix goes in meanwhile (App.gnss_update).
|
# 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
|
get "/api/trip/log" do
|
||||||
require_login!
|
require_login!
|
||||||
|
|||||||
+100
-45
@@ -1,5 +1,6 @@
|
|||||||
require "json"
|
require "json"
|
||||||
require "time"
|
require "time"
|
||||||
|
require "fileutils"
|
||||||
require_relative "track_stats"
|
require_relative "track_stats"
|
||||||
require_relative "gnss_sim"
|
require_relative "gnss_sim"
|
||||||
|
|
||||||
@@ -8,37 +9,43 @@ module Maptool
|
|||||||
# a trip is a library folder, Trips/<date> <name>. Start makes it — with
|
# a trip is a library folder, Trips/<date> <name>. Start makes it — with
|
||||||
# the planned route and its named stops in it — and from then on every
|
# 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
|
# 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
|
# track there.
|
||||||
# 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).
|
# Crash-safe like a FIT file, by being append-only: each point is a line
|
||||||
|
# appended to the trip's journal (<dir>/<started_at>.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
|
class TripLog
|
||||||
MIN_STEP_M = 10
|
MIN_STEP_M = 10
|
||||||
FLUSH_EVERY_S = 60
|
FSYNC_EVERY_S = 5
|
||||||
|
LIBRARY_EVERY_S = 300
|
||||||
ROOT = "Trips".freeze
|
ROOT = "Trips".freeze
|
||||||
|
|
||||||
def initialize(path, library:)
|
def initialize(dir, library:)
|
||||||
@path = path
|
@dir = dir
|
||||||
@library = library
|
@library = library
|
||||||
@mutex = Mutex.new
|
@mutex = Mutex.new
|
||||||
@state = begin
|
FileUtils.mkdir_p(dir)
|
||||||
JSON.parse(File.read(path), symbolize_names: true)
|
@trip = resume
|
||||||
rescue Errno::ENOENT, JSON::ParserError
|
@synced_at = @built_at = 0
|
||||||
{}
|
|
||||||
end
|
|
||||||
@flushed_at = 0
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def active?
|
def active?
|
||||||
@mutex.synchronize { !!@state[:folder] }
|
@mutex.synchronize { !!@trip }
|
||||||
end
|
end
|
||||||
|
|
||||||
# { active:, folder:, started_at:, points:, distance_m: } — coordinates
|
# { active:, folder:, started_at:, points:, distance_m: } — coordinates
|
||||||
# from index `since` on with `since:` (the map draws the line as it grows).
|
# from index `since` on with `since:` (the map draws the line as it grows).
|
||||||
def status(since: nil)
|
def status(since: nil)
|
||||||
@mutex.synchronize do
|
@mutex.synchronize do
|
||||||
points = @state[:points] || []
|
points = @trip ? @trip[:points] : []
|
||||||
result = { active: !!@state[:folder], folder: @state[:folder], started_at: @state[:started_at], points: points.size,
|
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(3) })["distance_meters"] }
|
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[:coordinates] = points[since.to_i..].to_a.map { |p| p.first(2) } if since
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
@@ -48,7 +55,7 @@ module Maptool
|
|||||||
# folder as a route and points. Returns the folder.
|
# folder as a route and points. Returns the folder.
|
||||||
def start(name, plan: nil, stops: [], now: Time.now)
|
def start(name, plan: nil, stops: [], now: Time.now)
|
||||||
@mutex.synchronize do
|
@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(' ')}"
|
folder = "#{ROOT}/#{[now.strftime('%Y-%m-%d'), name.to_s.strip].reject(&:empty?).join(' ')}"
|
||||||
@library.create_folder(folder)
|
@library.create_folder(folder)
|
||||||
@@ -62,8 +69,11 @@ module Maptool
|
|||||||
features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } }
|
features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } }
|
||||||
end
|
end
|
||||||
@library.import_features(features, folder: folder) unless features.empty?
|
@library.import_features(features, folder: folder) unless features.empty?
|
||||||
@state = { folder: folder, started_at: now.to_i, points: [], item: nil }
|
started = now.to_i
|
||||||
save
|
@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
|
folder
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -71,54 +81,99 @@ module Maptool
|
|||||||
# A fix: [lon, lat], altitude (m, or nil), at (epoch seconds).
|
# A fix: [lon, lat], altitude (m, or nil), at (epoch seconds).
|
||||||
def record(lon, lat, alt, at)
|
def record(lon, lat, alt, at)
|
||||||
@mutex.synchronize do
|
@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
|
return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M
|
||||||
|
|
||||||
@state[:points] << [lon, lat, alt, at.to_f.round(1)]
|
point = [lon, lat, alt, at.to_f.round(1)]
|
||||||
flush if at.to_f - @flushed_at >= FLUSH_EVERY_S
|
@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
|
||||||
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
|
def stop
|
||||||
@mutex.synchronize do
|
@mutex.synchronize do
|
||||||
folder = @state[:folder] or return nil
|
return nil unless @trip
|
||||||
flush
|
|
||||||
@state = {}
|
build
|
||||||
save
|
journal(end: Time.now.to_i)
|
||||||
|
sync
|
||||||
|
@file&.close
|
||||||
|
@file = nil
|
||||||
|
folder = @trip[:folder]
|
||||||
|
@trip = nil
|
||||||
folder
|
folder
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
# The car's track into the library (made on the first flush, replaced
|
# The newest journal with no end: the trip still running.
|
||||||
# after), the state file with it.
|
def resume
|
||||||
def flush
|
Dir[File.join(@dir, "*.ndjson")].max_by { |path| File.basename(path, ".ndjson").to_i }&.then do |path|
|
||||||
points = @state[:points]
|
trip = nil
|
||||||
if points.size >= 2
|
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
|
||||||
|
end
|
||||||
|
|
||||||
|
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] }
|
coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
|
||||||
times = points.map { |p| Time.at(p[3]) }
|
times = points.map { |p| Time.at(p[3]) }
|
||||||
name = "Car #{Time.at(@state[:started_at]).strftime('%Y-%m-%d %H:%M')}"
|
name = "Car #{Time.at(@trip[:started_at]).strftime('%Y-%m-%d %H:%M')}"
|
||||||
feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates },
|
feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates },
|
||||||
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" }
|
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" }
|
||||||
.merge(TrackStats.compute(coordinates, times: times))
|
.merge(TrackStats.compute(coordinates, times: times))
|
||||||
.merge("profile" => TrackStats.build_profile(coordinates, times: times)) }
|
.merge("profile" => TrackStats.build_profile(coordinates, times: times)) }
|
||||||
if @state[:item]
|
if @trip[:item]
|
||||||
@library.update_feature(@state[:item], @state[:item].delete_prefix("item:"), feature)
|
@library.update_feature(@trip[:item], @trip[:item].delete_prefix("item:"), feature)
|
||||||
else
|
else
|
||||||
@state[:item] = @library.import_features([feature], folder: @state[:folder]).find { |key| key.start_with?("item:") }
|
@trip[:item] = @library.import_features([feature], folder: @trip[:folder]).find { |key| key.start_with?("item:") }
|
||||||
|
journal(item: @trip[:item])
|
||||||
|
sync
|
||||||
end
|
end
|
||||||
end
|
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)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -3529,6 +3529,9 @@ button.basemap-panel__link[hidden] { display: none; }
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.topbar__drive.active { background: var(--accent); border-color: var(--accent); color: #fff; }
|
.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 #sidebar,
|
||||||
html.driving .basemap-panel,
|
html.driving .basemap-panel,
|
||||||
html.driving .gpx-panel,
|
html.driving .gpx-panel,
|
||||||
|
|||||||
+42
-11
@@ -5,13 +5,20 @@ require "maptool/gpx_store"
|
|||||||
require "maptool/trip_log"
|
require "maptool/trip_log"
|
||||||
|
|
||||||
class TripLogTest < Minitest::Test
|
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
|
# 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
|
# apart become the car's track; stop builds it into the library.
|
||||||
# after); stop closes it.
|
|
||||||
def test_a_trip_records_into_its_folder
|
def test_a_trip_records_into_its_folder
|
||||||
Dir.mktmpdir do |dir|
|
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"))
|
lib = library(dir)
|
||||||
log = Maptool::TripLog.new(File.join(dir, "trip_log.json"), library: library)
|
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 } }
|
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))
|
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
|
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.0, 48.0, 150, 1000)
|
||||||
log.record(17.00001, 48.0, 150, 1001) # < 10 m: skipped
|
log.record(17.00001, 48.0, 150, 1001) # < 10 m: skipped
|
||||||
log.record(17.001, 48.0, 151, 1002)
|
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 3, log.status[:points]
|
||||||
assert_equal [[17.001, 48.0], [17.002, 48.0]], log.status(since: 1)[:coordinates]
|
assert_equal [[17.001, 48.0], [17.002, 48.0]], log.status(since: 1)[:coordinates]
|
||||||
assert_equal folder, log.stop
|
assert_equal folder, log.stop
|
||||||
refute log.active?
|
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
|
all = names(lib)
|
||||||
assert(library.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder
|
%w[Camp Plan].each { |name| assert_includes all, name }
|
||||||
assert_includes names.join(" "), "Camp"
|
assert_includes all, "Car 2026-12-01"
|
||||||
assert_includes names.join(" "), "Car 2026-12-01"
|
refute_includes all, "My position"
|
||||||
assert_includes names.join(" "), "Plan"
|
assert(lib.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder
|
||||||
refute_includes names.join(" "), "My position"
|
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
|
end
|
||||||
end
|
end
|
||||||
Reference in new issue
Block a user