Library sync OsmAnd-style: brick is the server, a client (the car's maptool, SYNC_SERVER_URL) syncs on its Sync button — pulls the server's rows, pushes its own with the source files the server lacks, newer updated_at wins; /api/sync/* guarded by SYNC_TOKEN (written into brick's .env by CI). TRUSTED_NETWORKS logs in the car's LAN (no Gitea offline); TAKEOUT_HOST_DIR for a server without the Takeout; bin/pull-maps.sh pulls map data one way while at home
CI / check (push) Successful in 22s
CI / deploy (push) Successful in 18s

This commit is contained in:
randy committed 2026-11-27 23:22:32 +01:00
1 parent 850a5946ad
commit dbe742321a
13 files changed
+460 -5

No files matched your search

+1
View File
@@ -118,6 +118,7 @@ jobs:
MQTT_URL=${{ vars.MQTT_URL || secrets.MQTT_URL }}
MQTT_USERNAME=${{ vars.MQTT_USERNAME || secrets.MQTT_USERNAME }}
MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }}
SYNC_TOKEN=${{ secrets.SYNC_TOKEN }}
EOF
chmod 600 /srv/podman/maptool/.env
+82 -2
View File
@@ -12,6 +12,8 @@ require_relative "lib/maptool/google_saved"
require_relative "lib/maptool/routing"
require_relative "lib/maptool/mqtt_client"
require_relative "lib/maptool/can"
require_relative "lib/maptool/sync"
require "ipaddr"
require_relative "lib/maptool/live_store"
require_relative "lib/maptool/livetrack_store"
require_relative "lib/maptool/livetrack_client"
@@ -205,9 +207,38 @@ module Maptool
token_url: "/login/oauth/access_token"
)
# The car's server (no internet, so no Gitea login): requests from
# these networks (comma-separated CIDRs) count as logged in. By the
# socket's own peer address, never X-Forwarded-For — and only for a
# server no reverse proxy sits in front of (behind one every request
# comes from the proxy's address).
TRUSTED_NETWORKS = ENV.fetch("TRUSTED_NETWORKS", "").split(",").map(&:strip).reject(&:empty?).map { |cidr| IPAddr.new(cidr) }
# Library sync (Sync), OsmAnd-style: brick is the server, a client
# (the car's) has SYNC_SERVER_URL and syncs on its Sync button. The same
# SYNC_TOKEN on both: the server's /api/sync/* answer only to it.
SYNC_TOKEN = ENV.fetch("SYNC_TOKEN", "")
SYNC_SERVER_URL = ENV.fetch("SYNC_SERVER_URL", "")
SYNC_CLIENT = SYNC_TOKEN.empty? || SYNC_SERVER_URL.empty? ? nil : Sync.new(server: SYNC_SERVER_URL, token: SYNC_TOKEN, library: LIBRARY, state_path: File.join(DATA_DIR, "sync_state.json"))
SYNC_MUTEX = Mutex.new
helpers do
def logged_in?
!!session[:user]
!!session[:user] || trusted_network?
end
def trusted_network?
return false if TRUSTED_NETWORKS.empty?
address = IPAddr.new(request.env["REMOTE_ADDR"].to_s.delete_prefix("::ffff:"))
TRUSTED_NETWORKS.any? { |network| network.include?(address) }
rescue IPAddr::Error
false
end
def require_sync_token!
given = request.env["HTTP_AUTHORIZATION"].to_s.delete_prefix("Bearer ")
halt 401, json(error: "sync token required") if SYNC_TOKEN.empty? || !Rack::Utils.secure_compare(given, SYNC_TOKEN)
end
def require_login!
@@ -372,7 +403,7 @@ module Maptool
end
get "/" do
erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION }
erb :index, locals: { logged_in: logged_in?, user: session[:user] || "local network", revision: REVISION, sync_client: !SYNC_CLIENT.nil? }
end
# Map legend + symbol browser. A view, not a static public/ page, so it
@@ -800,6 +831,55 @@ module Maptool
halt 404
end
# The client's side of a sync (Sync): its pull (whole rows after
# ?since=<rev>, an item's source file) and its push (rows, then the
# source files we said we lack).
get "/api/sync/changes" do
require_sync_token!
json LIBRARY.sync_changes(params[:since] || 0)
rescue ArgumentError, TypeError
halt 400, json(error: "since must be a number")
end
get "/api/sync/source/:id" do
require_sync_token!
path = LIBRARY.item_source(params[:id])
halt 404 unless path && File.file?(path)
send_file path
end
post "/api/sync/apply" do
require_sync_token!
missing = LIBRARY.apply_sync(JSON.parse(request.body.read))
json missing: missing.map { |item| item["id"] }
rescue JSON::ParserError, Library::InvalidValue
halt 400, json(error: "bad changes")
end
put "/api/sync/source/:id" do
require_sync_token!
row = LIBRARY.source_row(params[:id]) or halt 404
# Source files never change: one already here stays.
LIBRARY.store_source(row, request.body.read) unless File.exist?(LIBRARY.source_file(row["type"], row["source_path"]))
json ok: true
rescue Library::InvalidValue
halt 400, json(error: "bad source path")
end
# The Sync button (a client only): pull, then push, now.
post "/api/sync/run" do
require_login!
halt 404, json(error: "not a sync client") unless SYNC_CLIENT
halt 409, json(error: "a sync is already running") unless SYNC_MUTEX.try_lock
begin
json SYNC_CLIENT.run
rescue *Sync::NETWORK_ERRORS => e
halt 502, json(error: "sync with #{SYNC_SERVER_URL} failed: #{e.message}")
ensure
SYNC_MUTEX.unlock
end
end
# The sync feed (Library#changes): everything after ?since=<rev>.
# Login-only, like the other exports.
get "/api/library/changes" do
+37
View File
@@ -0,0 +1,37 @@
#!/bin/bash
# Map data, one way: the home server (brick) builds it, the car's server
# pulls it — only while at home (brick reachable), never over LTE. The
# library goes both ways on its own (lib/maptool/sync.rb), not here.
#
# Run by maptool-pull-maps.timer on the car's server (docs/deployment.adoc).
# The key it uses is limited on brick to read-only rsync of the data dir:
# command="python3 /usr/share/doc/packages/rsync/support/rrsync -ro /srv/podman/maptool/data",restrict ssh-ed25519 …
# so paths below are relative to brick's data/.
set -euo pipefail
SOURCE=${MAP_SOURCE:-randy@10.17.240.2}
DATA=${MAP_DATA:-/srv/podman/maptool/data}
FILES="offline.pmtiles offline.pmtiles.meta.json terrain.pmtiles terrain.pmtiles.meta.json offline_regions.json"
DIRS="routing places hiking_trails kiwix nps"
host=${SOURCE#*@}
if ! timeout 5 bash -c "</dev/tcp/$host/22" 2>/dev/null; then
echo "pull-maps: $host not reachable (not at home), skipping"
exit 0
fi
changes=$(mktemp)
trap 'rm -f "$changes"' EXIT
# Into a temp file, renamed when complete (rsync's default): the app and
# Valhalla keep reading the old copy until restarted.
for f in $FILES; do
rsync -a --partial-dir=.rsync-partial --out-format='%n' "$SOURCE:$f" "$DATA/$f" >> "$changes" 2>/dev/null || true
done
for d in $DIRS; do
rsync -a --delete-delay --partial-dir=.rsync-partial --out-format='%n' "$SOURCE:$d/" "$DATA/$d/" >> "$changes"
done
if grep -qv '/$' "$changes"; then
echo "pull-maps: $(grep -cv '/$' "$changes") files updated, restarting maptool"
sudo systemctl restart podman-compose@maptool.service
fi
+9 -1
View File
@@ -64,6 +64,13 @@ services:
# Google Takeout exports (the "Saved" lists), mounted below; app.rb
# imports a new one hourly. Remove both lines to turn it off.
TAKEOUT_DIR: /app/takeout
# Library sync (lib/maptool/sync.rb): the shared token on the server
# and its clients; a client also has the server's URL (Sync button).
SYNC_SERVER_URL: ${SYNC_SERVER_URL:-}
SYNC_TOKEN: ${SYNC_TOKEN:-}
# Only on a server with no reverse proxy in front (the car's): these
# networks count as logged in. Never on one behind a proxy.
TRUSTED_NETWORKS: ${TRUSTED_NETWORKS:-}
volumes:
# Uploaded GPX files and the offline PMTiles extract — kept outside
# the image so a rebuild/redeploy doesn't wipe them (see
@@ -89,7 +96,8 @@ services:
# SELinux and the backup tree is unlabeled_t, unreadable for a
# container; the root sync job is unaffected by the relabel and new
# files inherit the directory's label.
- /srv/backup/gdrive/my-drive/current/Takeout:/app/takeout:ro,z
# TAKEOUT_HOST_DIR: another server (the car's) points it at an empty dir.
- ${TAKEOUT_HOST_DIR:-/srv/backup/gdrive/my-drive/current/Takeout}:/app/takeout:ro,z
# Serves an offline Wikipedia ZIM for the popup's "Nearby on Wikipedia"
# link (see docs/development.adoc for where to get one and drop it in —
+39
View File
@@ -175,6 +175,45 @@ topics. Blank `MQTT_URL` turns it off. The URL needs a name the
container can resolve — `ha.local` (mDNS) doesn't resolve inside it,
`mqtt://ha.priesol.net:1883` does.
== The car's server (rpi-dev, later the van's CM5)
A second maptool on a Raspberry Pi (Debian, arm64, rootful podman +
podman-compose), laid out like brick's: `/srv/podman/maptool/{build,data,.env}`,
the same `podman-compose@.service` unit. Deployed by hand for now (the
working tree rsynced into `build/`), not by CI.
Its `.env` adds:
* `TRUSTED_NETWORKS` — the home/car LAN (and loopback): those requests
count as logged in, since Gitea's OAuth needs internet and its redirect
URL is brick's. Only on a server no reverse proxy sits in front of —
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.
=== Library sync (both ways, OsmAnd-style)
brick is the server, the car's maptool a client: the client's Sync button
(Tracks & Points header, shown only where `SYNC_SERVER_URL` is set) pulls
the server's changes, then pushes its own (`lib/maptool/sync.rb`; the
server's `GET /api/sync/changes`, `GET`/`PUT /api/sync/source/:id`,
`POST /api/sync/apply`, all guarded by the shared `SYNC_TOKEN`). Newer
`updated_at` wins, source files come along, progress in the client's
`data/sync_state.json`. Over the public URL, so no VPN is needed for it.
On brick the CI deploy writes `SYNC_TOKEN` (a Gitea secret) into `.env`.
=== Map data (one way)
`bin/pull-maps.sh`, run by `maptool-pull-maps.timer` (10 min after boot,
then every 6 h) as `randy`: rsyncs the pmtiles, routing, places, hiking
trails, the ZIM and the NPS maps from brick while brick is reachable, and
restarts maptool when something changed. Its key is limited on brick
(`~randy/.ssh/authorized_keys`) to a read-only rsync of the data dir:
----
command="python3 /usr/share/doc/packages/rsync/support/rrsync -ro /srv/podman/maptool/data",restrict ssh-ed25519 AAAA… rpi-dev maptool map sync
----
== Garmin LiveTrack session webhook
`POST /api/livetrack/session` (`session_id`, `session_token`, `secret` form
+81 -1
View File
@@ -209,7 +209,7 @@ module Maptool
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ? AND deleted_at IS NULL", [id]) }
return nil unless source
type == "layer" ? @gpx_store.resolve_file(source) : File.join(@sources_dir, source)
source_file(type, source)
end
# --- writes -------------------------------------------------------------
@@ -457,6 +457,86 @@ module Maptool
raise InvalidValue
end
# --- server ⇄ server sync (home ⇄ car) -----------------------------------
SYNC_FOLDER_COLUMNS = %w[id parent_id name created_at updated_at deleted_at].freeze
SYNC_ITEM_COLUMNS = %w[id folder_id parent_id type name geometry properties fingerprint source_path created_at updated_at deleted_at].freeze
# Whole rows written after `since`, tombstones included, at most `limit`
# of each table; "next" is the rev to ask from next time (below "rev"
# while there's more).
def sync_changes(since, limit: 500)
since = Integer(since)
connect do |db|
db.transaction do
rev = db.get_first_value("SELECT rev FROM meta")
tables = { "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.to_h do |table, columns|
rows = db.execute("SELECT #{columns.join(', ')}, rev FROM #{table} WHERE rev > ? ORDER BY rev LIMIT ?", [since, limit])
[table, rows.map { |row| (columns + ["rev"]).zip(row).to_h }]
end
full = tables.values.select { |rows| rows.size == limit }.map { |rows| rows.last["rev"] - 1 }
tables.merge("rev" => rev, "next" => [rev, *full].min)
end
end
end
# Takes the other server's rows (sync_changes): one newer than ours —
# or not here yet — replaces ours, else ours stays (last writer wins by
# updated_at; an echo of our own change ties and is skipped). Returns
# the source files (items' source_path) not here yet.
# ponytail: the losing version isn't kept; a history table if a lost
# edit ever matters.
def apply_sync(changes)
missing = []
write do |db, rev, _now|
{ "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.each do |table, columns|
(changes[table] || []).each do |row|
ours = db.get_first_value("SELECT updated_at FROM #{table} WHERE id = ?", [row["id"]])
next if ours && ours >= row["updated_at"].to_s
db.execute("INSERT OR REPLACE INTO #{table} (#{columns.join(', ')}, rev) VALUES (#{(['?'] * (columns.size + 1)).join(', ')})",
[*row.values_at(*columns), rev])
missing << row if table == "items" && row["source_path"] && !row["deleted_at"] && !File.exist?(source_file(row["type"], row["source_path"]))
end
end
end
missing
end
# Where an item's source file lives: a legacy layer's in GpxStore,
# an upload's under sources/.
# The path comes from the other server too: never outside sources/.
def source_file(type, source_path)
return @gpx_store.resolve_file(source_path) if type == "layer"
root = File.expand_path(@sources_dir)
path = File.expand_path(File.join(root, source_path.to_s))
raise InvalidValue unless path.start_with?("#{root}/")
path
end
# An item's source file (tombstoned or not: the other server may still
# need it), nil without one.
def item_source(id)
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
source && source_file(type, source)
end
# An item's type and source_path (where its file belongs), nil without one.
def source_row(id)
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
source && { "type" => type, "source_path" => source }
end
# The other server's copy of a source file, written into place.
def store_source(item, bytes)
path = source_file(item["type"], item["source_path"])
FileUtils.mkdir_p(File.dirname(path))
File.binwrite("#{path}.part", bytes)
File.rename("#{path}.part", path)
end
# A folder's own items (not its subfolders') as one GPX with points and
# tracks together — what Locus imports into one folder.
def export_gpx(path)
+79
View File
@@ -0,0 +1,79 @@
require "json"
require "net/http"
require "uri"
module Maptool
# Library sync of a client server (the car's) against the main one
# (brick, the "cloud"), like OsmAnd's cloud sync: the client syncs when
# asked (the Sync button), the main server only answers. One run pulls
# what the server has that we haven't seen (Library#sync_changes over
# GET /api/sync/changes, applied by Library#apply_sync), then pushes ours
# (POST /api/sync/apply) with the source files the server lacks. Newer
# updated_at wins either way; the echo of a synced change ties and stops.
# Map data isn't synced here (bin/pull-maps.sh, one way).
class Sync
class Error < StandardError; end
NETWORK_ERRORS = [Error, JSON::ParserError, SocketError, SystemCallError, IOError,
Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError].freeze
def initialize(server:, token:, library:, state_path:)
@server = server.chomp("/")
@token = token
@library = library
@state_path = state_path
end
# { pulled:, pushed: } rows.
def run
{ pulled: pull, pushed: push }
end
def pull
count = 0
loop do
changes = JSON.parse(request(Net::HTTP::Get, "/api/sync/changes?since=#{state.fetch('pull', 0)}"))
@library.apply_sync(changes).each { |item| @library.store_source(item, request(Net::HTTP::Get, "/api/sync/source/#{item['id']}")) }
count += rows(changes)
save("pull" => changes["next"])
return count if changes["next"] >= changes["rev"]
end
end
def push
count = 0
loop do
changes = @library.sync_changes(state.fetch("push", 0))
missing = JSON.parse(request(Net::HTTP::Post, "/api/sync/apply", JSON.generate(changes)))["missing"]
missing.each { |id| request(Net::HTTP::Put, "/api/sync/source/#{id}", File.binread(@library.item_source(id))) }
count += rows(changes)
save("push" => changes["next"])
return count if changes["next"] >= changes["rev"]
end
end
private
def rows(changes) = changes.values_at("folders", "items").sum { |r| r&.size || 0 }
def request(kind, path, body = nil)
uri = URI("#{@server}#{path}")
req = kind.new(uri, "Authorization" => "Bearer #{@token}", "Content-Type" => "application/octet-stream")
req.body = body if body
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 10, read_timeout: 120) { |http| http.request(req) }
raise Error, "#{path.split('?').first}: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
response.body
end
# { "pull" => the server's rev we have up to, "push" => our rev it has up to }
def state
File.exist?(@state_path) ? JSON.parse(File.read(@state_path)) : {}
end
def save(values)
File.write("#{@state_path}.tmp", JSON.generate(state.merge(values)))
File.rename("#{@state_path}.tmp", @state_path)
end
end
end
+30
View File
@@ -8,6 +8,7 @@ import {
TRACK_ICON,
ROUTE_ICON,
DOWNLOAD_ICON,
SYNC_ICON,
MAP_MARKER_ICON,
POI_ICONS,
PARK4NIGHT_TAGS,
@@ -134,6 +135,17 @@ export class GpxPanelControl {
// The top level's own items have no folder row with a menu of its own.
const close = this._panel.querySelector(".gpx-panel__close");
close.before(this._menuButton(DOWNLOAD_ICON, "Export the top level", this._exportEntries("", "MapTool")));
// A sync client (the car's server) syncs with the main one on demand.
if ("syncClient" in this._panel.dataset) {
const sync = document.createElement("button");
sync.type = "button";
sync.className = "gpx-panel__action";
sync.title = "Sync with the main server";
sync.setAttribute("aria-label", sync.title);
sync.innerHTML = SYNC_ICON;
sync.addEventListener("click", () => this._sync(sync));
close.before(sync);
}
}
this._panel
.querySelector(".gpx-panel__close")
@@ -1403,6 +1415,24 @@ export class GpxPanelControl {
}
}
async _sync(button) {
button.disabled = true;
this._setStatus("Syncing…");
try {
const response = await fetch("/api/sync/run", { method: "POST" });
if (redirectIfUnauthorized(response)) return;
const body = await response.json();
if (!response.ok) return this._setStatus(body.error || "Sync failed.");
this._setStatus(`Synced: ${body.pulled} from the server, ${body.pushed} sent.`);
await this._loadTree();
await Promise.all([...this._visible].map((path) => this._reloadFile(path)));
} catch {
this._setStatus("Sync failed: the server is unreachable.");
} finally {
button.disabled = false;
}
}
_setStatus(text) {
this._uploadStatus.hidden = false;
this._uploadStatus.textContent = text;
+2
View File
@@ -8,6 +8,7 @@ import {
mdiBugOutline,
mdiClockOutline,
mdiCloudDownloadOutline,
mdiCloudSyncOutline,
mdiContentSaveOutline,
mdiCrosshairsGps,
mdiDeleteSweepOutline,
@@ -58,6 +59,7 @@ export const RADAR_CLOUD_ICON = mdi(mdiRadar);
export const TERRAIN_SHADOW_ICON = mdi(mdiSunAngleOutline);
export const CONTOUR_ICON = mdi(mdiBacteriaOutline);
export const OFFLINE_DATA_ICON = mdi(mdiCloudDownloadOutline);
export const SYNC_ICON = mdi(mdiCloudSyncOutline);
export const DEBUG_ICON = mdi(mdiBugOutline);
export const WIKI_ICON = mdi(mdiWikipedia);
export const LIVETRACK_ICON = mdi(mdiMapMarkerRadiusOutline);
+1
View File
@@ -3,6 +3,7 @@ export const mdiBacteriaOutline = "M9,2H7V4.1C6.29,4.25 5.73,4.54 5.32,4.91L2.7,
export const mdiBugOutline = "M20,8H17.19C16.74,7.2 16.12,6.5 15.37,6L17,4.41L15.59,3L13.42,5.17C12.96,5.06 12.5,5 12,5C11.5,5 11.05,5.06 10.59,5.17L8.41,3L7,4.41L8.62,6C7.87,6.5 7.26,7.21 6.81,8H4V10H6.09C6.03,10.33 6,10.66 6,11V12H4V14H6V15C6,15.34 6.03,15.67 6.09,16H4V18H6.81C8.47,20.87 12.14,21.84 15,20.18C15.91,19.66 16.67,18.9 17.19,18H20V16H17.91C17.97,15.67 18,15.34 18,15V14H20V12H18V11C18,10.66 17.97,10.33 17.91,10H20V8M16,15A4,4 0 0,1 12,19A4,4 0 0,1 8,15V11A4,4 0 0,1 12,7A4,4 0 0,1 16,11V15M14,10V12H10V10H14M10,14H14V16H10V14Z";
export const mdiClockOutline = "M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z";
export const mdiCloudDownloadOutline = "M6.5 20Q4.22 20 2.61 18.43 1 16.85 1 14.58 1 12.63 2.17 11.1 3.35 9.57 5.25 9.15 5.68 7.35 7.38 5.73 9.07 4.1 11 4.1 11.83 4.1 12.41 4.69 13 5.28 13 6.1V12.15L14.6 10.6L16 12L12 16L8 12L9.4 10.6L11 12.15V6.1Q9.1 6.45 8.05 7.94 7 9.43 7 11H6.5Q5.05 11 4.03 12.03 3 13.05 3 14.5 3 15.95 4.03 17 5.05 18 6.5 18H18.5Q19.55 18 20.27 17.27 21 16.55 21 15.5 21 14.45 20.27 13.73 19.55 13 18.5 13H17V11Q17 9.8 16.45 8.76 15.9 7.73 15 7V4.68Q16.85 5.55 17.93 7.26 19 9 19 11 20.73 11.2 21.86 12.5 23 13.78 23 15.5 23 17.38 21.69 18.69 20.38 20 18.5 20M12 11.05Z";
export const mdiCloudSyncOutline = "M13.03 18C13.08 18.7 13.24 19.38 13.5 20H6.5C5 20 3.69 19.5 2.61 18.43C1.54 17.38 1 16.09 1 14.58C1 13.28 1.39 12.12 2.17 11.1S4 9.43 5.25 9.15C5.67 7.62 6.5 6.38 7.75 5.43S10.42 4 12 4C13.95 4 15.6 4.68 16.96 6.04C18.32 7.4 19 9.05 19 11C19.04 11 19.07 11 19.1 11C18.36 11.07 17.65 11.23 17 11.5V11C17 9.62 16.5 8.44 15.54 7.46C14.56 6.5 13.38 6 12 6S9.44 6.5 8.46 7.46C7.5 8.44 7 9.62 7 11H6.5C5.53 11 4.71 11.34 4.03 12.03C3.34 12.71 3 13.53 3 14.5S3.34 16.29 4.03 17C4.71 17.66 5.53 18 6.5 18H13.03M19 13.5V12L16.75 14.25L19 16.5V15C20.38 15 21.5 16.12 21.5 17.5C21.5 17.9 21.41 18.28 21.24 18.62L22.33 19.71C22.75 19.08 23 18.32 23 17.5C23 15.29 21.21 13.5 19 13.5M19 20C17.62 20 16.5 18.88 16.5 17.5C16.5 17.1 16.59 16.72 16.76 16.38L15.67 15.29C15.25 15.92 15 16.68 15 17.5C15 19.71 16.79 21.5 19 21.5V23L21.25 20.75L19 18.5V20Z";
export const mdiContentSaveOutline = "M17 3H5C3.89 3 3 3.9 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V7L17 3M19 19H5V5H16.17L19 7.83V19M12 12C10.34 12 9 13.34 9 15S10.34 18 12 18 15 16.66 15 15 13.66 12 12 12M6 6H15V10H6V6Z";
export const mdiCrosshairsGps = "M12,8A4,4 0 0,1 16,12A4,4 0 0,1 12,16A4,4 0 0,1 8,12A4,4 0 0,1 12,8M3.05,13H1V11H3.05C3.5,6.83 6.83,3.5 11,3.05V1H13V3.05C17.17,3.5 20.5,6.83 20.95,11H23V13H20.95C20.5,17.17 17.17,20.5 13,20.95V23H11V20.95C6.83,20.5 3.5,17.17 3.05,13M12,5A7,7 0 0,0 5,12A7,7 0 0,0 12,19A7,7 0 0,0 19,12A7,7 0 0,0 12,5Z";
export const mdiDeleteSweepOutline = "M15,16H19V18H15V16M15,8H22V10H15V8M15,12H21V14H15V12M11,10V18H5V10H11M13,8H3V18A2,2 0 0,0 5,20H11A2,2 0 0,0 13,18V8M14,5H11L10,4H6L5,5H2V7H14V5Z";
+15
View File
@@ -137,6 +137,21 @@ class AppTest < Minitest::Test
assert_equal 401, request.get("/api/live").status
end
def test_the_sync_feed_needs_the_sync_token
# No SYNC_TOKEN in tests: closed, even with a login or an empty bearer.
assert_equal 401, request.get("/api/sync/changes").status
assert_equal 401, request.get("/api/sync/changes", "HTTP_AUTHORIZATION" => "Bearer ", **logged_in_env).status
assert_equal 401, request.get("/api/sync/source/x").status
assert_equal 401, request.post("/api/sync/apply", input: "{}").status
assert_equal 401, request.put("/api/sync/source/x", input: "x").status
end
def test_the_sync_button_is_only_a_clients
assert_equal 401, request.post("/api/sync/run").status
assert_equal 404, request.post("/api/sync/run", **logged_in_env).status
refute_includes request.get("/", **logged_in_env).body, "data-sync-client"
end
def test_can_requires_login_and_is_off_without_a_config
assert_equal 401, request.get("/api/can").status
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "available" => false }, json_body(request.get("/api/can", **logged_in_env)))
+83
View File
@@ -0,0 +1,83 @@
require_relative "test_helper"
require "maptool/library"
require "stringio"
# Two servers' libraries (home, car) exchanging Library#sync_changes /
# #apply_sync the way Maptool::Sync does over HTTP.
class SyncTest < Minitest::Test
def setup
@dir = Dir.mktmpdir
@home = library("home")
@car = library("car")
end
def teardown
FileUtils.remove_entry(@dir)
end
def test_changes_flow_both_ways_with_source_files_and_stop_echoing
@home.import(folder: "Rides", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
pull(@car, from: @home)
assert_equal ["Rides"], @car.tree["children"].map { |c| c["name"] }
track = @car.tree["children"][0]["children"].find { |c| c["path"].start_with?("item:") }
assert File.exist?(@car.original(track["path"])), "the upload's source file came along"
@car.create_folder("Car notes")
pull(@home, from: @car)
assert_equal ["Car notes", "Rides"], @home.tree["children"].map { |c| c["name"] }.sort
# Each side's echo of what it just took ties and changes nothing more.
assert_equal 0, pull(@car, from: @home)
assert_equal 0, pull(@home, from: @car)
end
def test_the_later_edit_wins_and_a_delete_carries_over
@home.create_folder("Trip")
pull(@car, from: @home)
sleep 1.1 # updated_at has second resolution
@car.rename_folder("Trip", "Trip 2026")
pull(@home, from: @car)
assert_equal ["Trip 2026"], @home.tree["children"].map { |c| c["name"] }
stale = @home.sync_changes(0)
stale["folders"].each { |f| f["updated_at"] = "2000-01-01T00:00:00Z"; f["name"] = "Old" }
@car.apply_sync(stale)
assert_equal ["Trip 2026"], @car.tree["children"].map { |c| c["name"] }, "an older version doesn't overwrite"
end
def test_pages_until_caught_up
3.times { |i| @home.create_folder("F#{i}") }
since = 0
pages = 0
loop do
changes = @home.sync_changes(since, limit: 2)
@car.apply_sync(changes)
pages += 1
since = changes["next"]
break if since >= changes["rev"]
end
assert_equal %w[F0 F1 F2], @car.tree["children"].map { |c| c["name"] }
assert_operator pages, :>, 1
end
def test_a_source_path_from_the_other_server_stays_inside_sources
row = { "id" => "x", "type" => "track", "source_path" => "../../etc/passwd", "updated_at" => "2030-01-01T00:00:00Z", "properties" => "{}", "created_at" => "2030-01-01T00:00:00Z" }
assert_raises(Maptool::Library::InvalidValue) { @car.apply_sync("items" => [row]) }
end
private
def library(name)
Maptool::Library.new(File.join(@dir, name, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(@dir, name, "gpx")),
sources_dir: File.join(@dir, name, "sources"))
end
# What Sync#pull does, without HTTP (since 0 is fine: idempotent).
# Returns how many rows `target` took.
def pull(target, from:)
before = target.sync_changes(0)["rev"]
missing = target.apply_sync(from.sync_changes(0))
missing.each { |item| target.store_source(item, File.binread(from.item_source(item["id"]))) }
target.sync_changes(before).values_at("folders", "items").sum(&:size)
end
end
+1 -1
View File
@@ -58,7 +58,7 @@
</div>
</div>
<div id="gpx-panel" class="gpx-panel" hidden>
<div id="gpx-panel" class="gpx-panel" hidden<%= " data-sync-client" if sync_client %>>
<div class="gpx-panel__header">
<strong>Tracks &amp; Points</strong>
<div class="gpx-panel__actions">