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
This commit is contained in:
1 parent
850a5946ad
commit
dbe742321a
13 files changed
+460
-5
No files matched your search
+81
-1
@@ -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)
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user