The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
342 lines
16 KiB
Python
342 lines
16 KiB
Python
"""Sync groundwork in the plugins' SQLite files: every synced row gets an id no other device
|
|
will make (`_uid`), a change stamp (`_hlc`) and the device that made the change (`_dev`); deletes
|
|
leave a marker (`_sync_tomb`). SQLite triggers keep them up to date, so plugin code writes its
|
|
tables as before. sync.py moves the changes between devices (encrypted, through the server).
|
|
|
|
A plugin says what syncs in its META:
|
|
|
|
"sync": {"food.db": { # file under dash_data/<plugin>/
|
|
"food": {"refs_in": {"recipe": "my:"}}, # "my:12" inside that text = food 12
|
|
"entry": {"key": "'src:' || NEW.src_id", # natural id (SQL on NEW), else random
|
|
"refs": {"my_food_id": "food"}}, # integer column → a row of that table
|
|
}}
|
|
|
|
Tables are applied in the order given (a table before the ones pointing at it).
|
|
- key: SQL on NEW giving a stable id when the row has a natural one (a day, an import's id) — two
|
|
devices making "the same" row then agree on it, and INSERT OR REPLACE keeps its identity. NULL
|
|
from it = a random id. A row whose key changes (a measurement moved to another day) becomes a
|
|
delete of the old id + the new one.
|
|
- refs: integer foreign keys, sent as the target's _uid and turned back into the local id.
|
|
- refs_in: text columns holding "<prefix><local id>" (JSON) — sent as "<prefix>~<uid>".
|
|
- fork: [columns] — rows are documents (notes): those columns are a version of the text, named by
|
|
`rev` (new at every edit) with `revs` (the last ones, space-separated, newest last) beside it.
|
|
A change written on top of the other side's version wins its text whatever the stamps say (the
|
|
other columns — pinned, folder — still go by the stamp); two versions written at the same time:
|
|
the later one wins, the other is kept as a row of its own, `_uid` "copy:<its rev>", `origin` =
|
|
that rev — every device makes the same copy, so they agree without sending it.
|
|
|
|
_hlc is milliseconds since 1970, but never smaller than the last stamp + 1 (and pushed past what
|
|
arrives from other devices), so stamps keep their order even with a clock that's off. Ties: the
|
|
higher _dev wins. Changes applied from elsewhere keep their stamp and device (the triggers stand
|
|
aside while `applying` is 1 — set inside the applying transaction only).
|
|
"""
|
|
import json
|
|
import re
|
|
import sqlite3
|
|
import uuid
|
|
|
|
NOW_MS = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)"
|
|
META_SQL = """
|
|
CREATE TABLE IF NOT EXISTS _sync_meta (k TEXT PRIMARY KEY, v);
|
|
CREATE TABLE IF NOT EXISTS _sync_tomb (tbl TEXT NOT NULL, uid TEXT NOT NULL, hlc INTEGER NOT NULL, dev TEXT NOT NULL,
|
|
PRIMARY KEY (tbl, uid));
|
|
"""
|
|
CLOCK = "(SELECT v FROM _sync_meta WHERE k = 'clock')"
|
|
DEV = "(SELECT v FROM _sync_meta WHERE k = 'dev')"
|
|
QUIET = "(SELECT v FROM _sync_meta WHERE k = 'applying') = 0"
|
|
BUMP = f"UPDATE _sync_meta SET v = max(v + 1, {NOW_MS}) WHERE k = 'clock';"
|
|
RANDOM = "lower(hex(randomblob(16)))"
|
|
|
|
|
|
def connect(path):
|
|
con = sqlite3.connect(path, timeout=30)
|
|
con.row_factory = sqlite3.Row
|
|
return con
|
|
|
|
|
|
def _cols(con, t):
|
|
return [r["name"] for r in con.execute(f"PRAGMA table_info({t})")]
|
|
|
|
|
|
def _alias(con, t):
|
|
"""The INTEGER PRIMARY KEY column (= the rowid, local only), or None."""
|
|
pk = [r for r in con.execute(f"PRAGMA table_info({t})") if r["pk"]]
|
|
return pk[0]["name"] if len(pk) == 1 and pk[0]["type"].upper() == "INTEGER" else None
|
|
|
|
|
|
def prepare(path, tables, dev):
|
|
"""Columns, markers, triggers — idempotent, at every start. Rows from before get their ids
|
|
and a stamp now (so a first sync sends them)."""
|
|
con = connect(path)
|
|
try:
|
|
con.executescript(META_SQL)
|
|
con.execute("INSERT OR IGNORE INTO _sync_meta VALUES ('clock', 0), ('applying', 0), ('pushed', 0)")
|
|
con.execute("INSERT OR REPLACE INTO _sync_meta VALUES ('dev', ?)", (dev,))
|
|
con.execute("UPDATE _sync_meta SET v = 0 WHERE k = 'applying'") # a crash mid-apply
|
|
for t, spec in tables.items():
|
|
have = _cols(con, t)
|
|
if not have:
|
|
continue # not created yet (the plugin makes it on first use)
|
|
for c, typ in (("_uid", "TEXT"), ("_hlc", "INTEGER"), ("_dev", "TEXT")):
|
|
if c not in have:
|
|
con.execute(f"ALTER TABLE {t} ADD COLUMN {c} {typ}")
|
|
con.execute(f"CREATE INDEX IF NOT EXISTS _sync_{t}_uid ON {t} (_uid)")
|
|
con.execute(f"CREATE INDEX IF NOT EXISTS _sync_{t}_hlc ON {t} (_hlc)")
|
|
key = spec.get("key")
|
|
new_uid = f"coalesce({key}, {RANDOM})" if key else RANDOM
|
|
for trig in ("i", "u", "d"):
|
|
con.execute(f"DROP TRIGGER IF EXISTS _sync_{t}_{trig}")
|
|
# rows from before the triggers: their ids + a stamp (NEW. → the row itself)
|
|
if con.execute(f"SELECT 1 FROM {t} WHERE _uid IS NULL LIMIT 1").fetchone():
|
|
con.execute(BUMP)
|
|
con.execute(f"UPDATE {t} SET _uid = {new_uid.replace('NEW.', '')}, _hlc = {CLOCK}, _dev = {DEV} "
|
|
"WHERE _uid IS NULL")
|
|
con.executescript(f"""
|
|
CREATE TRIGGER _sync_{t}_i AFTER INSERT ON {t} WHEN {QUIET} BEGIN
|
|
{BUMP}
|
|
UPDATE {t} SET _uid = coalesce(NEW._uid, {new_uid}), _hlc = {CLOCK}, _dev = {DEV} WHERE rowid = NEW.rowid;
|
|
END;
|
|
CREATE TRIGGER _sync_{t}_u AFTER UPDATE ON {t} WHEN {QUIET} AND OLD._uid IS NOT NULL AND NEW._hlc IS OLD._hlc BEGIN
|
|
{BUMP}
|
|
{f'''INSERT OR REPLACE INTO _sync_tomb SELECT '{t}', OLD._uid, {CLOCK}, {DEV} WHERE ({key}) IS NOT NULL AND ({key}) IS NOT OLD._uid;
|
|
UPDATE {t} SET _uid = coalesce({key}, OLD._uid) WHERE rowid = NEW.rowid;''' if key else ''}
|
|
UPDATE {t} SET _hlc = {CLOCK}, _dev = {DEV} WHERE rowid = NEW.rowid;
|
|
END;
|
|
CREATE TRIGGER _sync_{t}_d AFTER DELETE ON {t} WHEN {QUIET} AND OLD._uid IS NOT NULL BEGIN
|
|
{BUMP}
|
|
INSERT OR REPLACE INTO _sync_tomb VALUES ('{t}', OLD._uid, {CLOCK}, {DEV});
|
|
END;""")
|
|
con.commit()
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def _meta(con, k):
|
|
r = con.execute("SELECT v FROM _sync_meta WHERE k = ?", (k,)).fetchone()
|
|
return r[0] if r else None
|
|
|
|
|
|
def _uid_of(con, t, rowid):
|
|
if rowid is None:
|
|
return None
|
|
r = con.execute(f"SELECT _uid FROM {t} WHERE rowid = ?", (rowid,)).fetchone()
|
|
return r[0] if r else None
|
|
|
|
|
|
def _id_of(con, t, uid):
|
|
if uid is None:
|
|
return None
|
|
r = con.execute(f"SELECT rowid FROM {t} WHERE _uid = ?", (uid,)).fetchone()
|
|
return r[0] if r else None
|
|
|
|
|
|
def _refs_out(con, text, prefix, t):
|
|
if not text:
|
|
return text
|
|
return re.sub(re.escape(prefix) + r"(\d+)\b",
|
|
lambda m: prefix + "~" + (_uid_of(con, t, int(m.group(1))) or "gone"), text)
|
|
|
|
|
|
def _refs_back(con, text, prefix, t):
|
|
"""→ (text with local ids, how many weren't found)."""
|
|
if not text:
|
|
return text, 0
|
|
missing = 0
|
|
def back(m):
|
|
nonlocal missing
|
|
i = _id_of(con, t, m.group(1))
|
|
if i is None and m.group(1) != "gone":
|
|
missing += 1
|
|
return prefix + str(i if i is not None else 0) # 0 = not here (any more): reads as gone
|
|
return re.sub(re.escape(prefix) + r"~([0-9a-z]+)", back, text), missing
|
|
|
|
|
|
def changes(path, tables, name):
|
|
"""This device's changes since the last push: ([change], mark). Tables are named
|
|
"<plugin>.<table>" in the changes ("food.entry"); call mark_pushed(path, mark) once sent."""
|
|
con = connect(path)
|
|
try:
|
|
dev, since = _meta(con, "dev"), _meta(con, "pushed") or 0
|
|
mark, out = since, []
|
|
for t, spec in tables.items():
|
|
cols = _cols(con, t)
|
|
if not cols:
|
|
continue
|
|
alias = _alias(con, t)
|
|
keep = [c for c in cols if c not in (alias, "_uid", "_hlc", "_dev")]
|
|
for r in con.execute(f"SELECT * FROM {t} WHERE _dev = ? AND _hlc > ? ORDER BY _hlc", (dev, since)):
|
|
row = {c: r[c] for c in keep}
|
|
for c, ref in spec.get("refs", {}).items():
|
|
row[c] = _uid_of(con, ref, row[c])
|
|
for c, prefix in spec.get("refs_in", {}).items():
|
|
row[c] = _refs_out(con, row[c], prefix, t)
|
|
out.append({"t": f"{name}.{t}", "u": r["_uid"], "h": r["_hlc"], "d": dev, "row": row})
|
|
mark = max(mark, r["_hlc"])
|
|
for r in con.execute("SELECT * FROM _sync_tomb WHERE dev = ? AND hlc > ? ORDER BY hlc", (dev, since)):
|
|
if r["tbl"] in tables:
|
|
out.append({"t": f"{name}.{r['tbl']}", "u": r["uid"], "h": r["hlc"], "d": dev, "del": True})
|
|
mark = max(mark, r["hlc"])
|
|
return out, mark
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def is_empty(path, tables):
|
|
"""Nothing synced in this file yet (no rows, no delete markers)? Read only."""
|
|
con = connect(path)
|
|
try:
|
|
return not con.execute("SELECT 1 FROM _sync_tomb LIMIT 1").fetchone() and not any(
|
|
con.execute(f"SELECT 1 FROM {t} LIMIT 1").fetchone() for t in tables if _cols(con, t))
|
|
except sqlite3.Error:
|
|
return False
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def mark_pushed(path, mark):
|
|
con = connect(path)
|
|
try:
|
|
con.execute("UPDATE _sync_meta SET v = max(v, ?) WHERE k = 'pushed'", (mark,))
|
|
con.commit()
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def _newer(h, d, lh, ld):
|
|
"""Does (h, d) win over the local (lh, ld)? Later stamp wins; on a tie the higher device."""
|
|
return (h, d) > (lh or 0, ld or "")
|
|
|
|
|
|
def apply(path, tables, name, items):
|
|
"""Changes from other devices (this file's part of a batch) → {applied, skipped, failed}.
|
|
Last change wins per row; a delete marker older than a row's change doesn't remove it."""
|
|
stats = {"applied": 0, "skipped": 0, "failed": 0}
|
|
mine = [c for c in items if c["t"].split(".", 1)[0] == name and c["t"].split(".", 1)[1] in tables]
|
|
if not mine:
|
|
return stats
|
|
con = connect(path)
|
|
try:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
con.execute("UPDATE _sync_meta SET v = 1 WHERE k = 'applying'")
|
|
top = max(c["h"] for c in mine)
|
|
con.execute("UPDATE _sync_meta SET v = max(v, ?) WHERE k = 'clock'", (top,))
|
|
for t, spec in tables.items():
|
|
cols = set(_cols(con, t))
|
|
if not cols:
|
|
continue
|
|
rows = [c for c in mine if c["t"] == f"{name}.{t}" and not c.get("del")]
|
|
# a table pointing at itself (a tree): parents first — whatever can't resolve yet waits a round
|
|
while rows:
|
|
later = []
|
|
for c in rows:
|
|
res = _apply_row(con, t, spec, cols, c)
|
|
if res == "wait":
|
|
later.append(c)
|
|
else:
|
|
stats[res] += 1
|
|
if len(later) == len(rows): # nothing moved: apply them with the parent missing
|
|
for c in later:
|
|
stats[_apply_row(con, t, spec, cols, c, force=True)] += 1
|
|
break
|
|
rows = later
|
|
for c in mine:
|
|
if not c.get("del"):
|
|
continue
|
|
t = c["t"].split(".", 1)[1]
|
|
r = con.execute(f"SELECT rowid AS rid, _hlc, _dev FROM {t} WHERE _uid = ?", (c["u"],)).fetchone()
|
|
tomb = con.execute("SELECT hlc, dev FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, c["u"])).fetchone()
|
|
if not tomb or _newer(c["h"], c["d"], tomb["hlc"], tomb["dev"]):
|
|
con.execute("INSERT OR REPLACE INTO _sync_tomb VALUES (?, ?, ?, ?)", (t, c["u"], c["h"], c["d"]))
|
|
if r and _newer(c["h"], c["d"], r["_hlc"], r["_dev"]):
|
|
con.execute(f"DELETE FROM {t} WHERE rowid = ?", (r["rid"],))
|
|
stats["applied"] += 1
|
|
else:
|
|
stats["skipped"] += 1
|
|
con.execute("UPDATE _sync_meta SET v = 0 WHERE k = 'applying'")
|
|
con.commit()
|
|
except Exception:
|
|
con.rollback()
|
|
raise
|
|
finally:
|
|
con.close()
|
|
return stats
|
|
|
|
|
|
def _apply_row(con, t, spec, cols, c, force=False):
|
|
row = {k: v for k, v in c["row"].items() if k in cols} # columns this side doesn't have (yet) are left out
|
|
for col, ref in spec.get("refs", {}).items():
|
|
if row.get(col) is None:
|
|
continue
|
|
local = _id_of(con, ref, row[col])
|
|
if local is None and ref == t and not force:
|
|
return "wait"
|
|
row[col] = local
|
|
for col, prefix in spec.get("refs_in", {}).items(): # rows of the same table (a meal's ingredients)
|
|
if col in row:
|
|
row[col], missing = _refs_back(con, row[col], prefix, t)
|
|
if missing and not force:
|
|
return "wait"
|
|
r = con.execute(f"SELECT rowid AS rid, _hlc, _dev FROM {t} WHERE _uid = ?", (c["u"],)).fetchone()
|
|
tomb = con.execute("SELECT hlc, dev FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, c["u"])).fetchone()
|
|
if tomb and not _newer(c["h"], c["d"], tomb["hlc"], tomb["dev"]):
|
|
return "skipped" # deleted later somewhere
|
|
try:
|
|
if r and spec.get("fork"):
|
|
done = _fork(con, t, spec["fork"], cols, c, row, r["rid"])
|
|
if done:
|
|
return done
|
|
if r:
|
|
if not _newer(c["h"], c["d"], r["_hlc"], r["_dev"]):
|
|
return "skipped"
|
|
sets = {**row, "_hlc": c["h"], "_dev": c["d"]}
|
|
con.execute(f"UPDATE {t} SET {', '.join(f'{k} = ?' for k in sets)} WHERE rowid = ?", (*sets.values(), r["rid"]))
|
|
else:
|
|
vals = {**row, "_uid": c["u"], "_hlc": c["h"], "_dev": c["d"]}
|
|
# a natural-key row both sides made before they had ids: take it over
|
|
con.execute(f"INSERT OR REPLACE INTO {t} ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})",
|
|
tuple(vals.values()))
|
|
except sqlite3.Error as e:
|
|
print(f"sync: {t} {c['u']}: {e}", flush=True)
|
|
return "failed"
|
|
return "applied"
|
|
|
|
|
|
def _fork(con, t, content, cols, c, row, rid):
|
|
"""A document row (spec "fork") meeting another version of itself → "applied" when settled
|
|
here, None = go on with the plain last-change-wins (after keeping a copy of the loser)."""
|
|
loc = dict(con.execute(f"SELECT * FROM {t} WHERE rowid = ?", (rid,)).fetchone())
|
|
mine, theirs = loc.get("rev"), row.get("rev")
|
|
if not mine or not theirs or mine == theirs:
|
|
return None # the same text: only the rest differs
|
|
win = _newer(c["h"], c["d"], loc["_hlc"], loc["_dev"])
|
|
text = (*content, "rev", "revs")
|
|
if mine in (row.get("revs") or "").split(): # written on top of ours: its text
|
|
if win:
|
|
return None
|
|
keep = {k: row[k] for k in text if k in row}
|
|
con.execute(f"UPDATE {t} SET {', '.join(f'{k} = ?' for k in keep)} WHERE rowid = ?", (*keep.values(), rid))
|
|
return "applied"
|
|
if theirs in (loc.get("revs") or "").split(): # ours was written on top of it: our text
|
|
if not win:
|
|
return None
|
|
# a new state (our text + their pin / folder): stamped here, so it goes out to the others —
|
|
# with their stamp our text would never be sent
|
|
con.execute(BUMP)
|
|
rest = {k: v for k, v in row.items() if k not in text}
|
|
con.execute(f"UPDATE {t} SET {''.join(f'{k} = ?, ' for k in rest)}_hlc = {CLOCK}, _dev = {DEV} WHERE rowid = ?",
|
|
(*rest.values(), rid))
|
|
return "applied"
|
|
# both written at the same time: the later one stays, the other becomes a copy
|
|
loser = loc if win else {**row, "_hlc": c["h"], "_dev": c["d"]}
|
|
uid = "copy:" + loser["rev"]
|
|
if not (con.execute(f"SELECT 1 FROM {t} WHERE _uid = ?", (uid,)).fetchone()
|
|
or con.execute("SELECT 1 FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, uid)).fetchone()):
|
|
alias = _alias(con, t)
|
|
vals = {**{k: v for k, v in loser.items() if k in cols and k not in (alias, "_uid")},
|
|
"origin": loser["rev"], "_uid": uid}
|
|
con.execute(f"INSERT INTO {t} ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})", tuple(vals.values()))
|
|
return None
|
|
|
|
|
|
def device_id():
|
|
return uuid.uuid4().hex[:12]
|