// The phone's copy of the synced data, kept in the wire format of PROTOCOL.md: one row per // (table, id) with its stamp, device and the columns as JSON — references are already ids there, // so nothing is translated (the dashboard's syncdb.py turns them into its integer keys; we don't // need to). The merge rules are syncdb.apply's: the later (stamp, device) wins per row, deletes // leave a marker, a change older than a marker is skipped, the clock only moves forward. // // rec (t "food.entry", u id, h stamp, d device, data JSON) // tomb (t, u, h, d) a delete marker // meta (k, v) clock, pushed (my newest stamp sent), pulled (server seq) import 'dart:convert'; import 'dart:math'; import 'package:sqlite3/sqlite3.dart'; class SyncStore { SyncStore(String path, this.device) : db = sqlite3.open(path) { db.execute('PRAGMA journal_mode = WAL'); db.execute('PRAGMA busy_timeout = 10000'); // the app and the background sync share the file db.execute(''' CREATE TABLE IF NOT EXISTS rec (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL, data TEXT NOT NULL, PRIMARY KEY (t, u)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS tomb (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL, PRIMARY KEY (t, u)) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS rec_mine ON rec (d, h); CREATE INDEX IF NOT EXISTS tomb_mine ON tomb (d, h); '''); } final Database db; final String device; // this device's id (12 hex), in every change it makes int meta(String k) => (db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as int?) ?? 0; void setMeta(String k, int v) => db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]); String? metaText(String k) => db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as String?; void setMetaText(String k, String? v) => v == null ? db.execute('DELETE FROM meta WHERE k = ?', [k]) : db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]); /// Tables whose rows are documents (syncdb.py "fork"): their text columns, versioned by rev / revs. /// Two versions written at the same time are both kept — the loser as "copy:" + its rev. static const forks = {'notes.note': ['body', 'updated']}; /// Tables the phone never reads — the dashboards' raw ActivityWatch data (every window, every minute of /// typing): not kept. What the app shows of it comes as the Pi's blocks (workload.act). static const skip = ['activity.']; static bool newer(int h, String d, int? lh, String? ld) => h != (lh ?? 0) ? h > (lh ?? 0) : d.compareTo(ld ?? '') > 0; /// A new local stamp: never below the last one + 1 (PROTOCOL.md "Stamps"). int _tick() { final h = max(meta('clock') + 1, DateTime.now().millisecondsSinceEpoch); setMeta('clock', h); return h; } // ---- reading ----------------------------------------------------------------------------- /// Every live row of a table ("food.entry") as {_u, _h (its change stamp), …columns}. List> rows(String t, {String? where, List args = const []}) => [ for (final r in db.select( 'SELECT u, h, data FROM rec WHERE t = ?${where == null ? '' : ' AND ($where)'}', [t, ...args])) {'_u': r['u'], '_h': r['h'], ...jsonDecode(r['data'] as String) as Map} ]; Map? row(String t, String u) { final r = db.select('SELECT data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; return r == null ? null : {'_u': u, ...jsonDecode(r['data'] as String) as Map}; } Map counts() => { for (final r in db.select('SELECT t, count(*) AS n FROM rec GROUP BY t ORDER BY t')) r['t'] as String: r['n'] as int }; // ---- writing here ------------------------------------------------------------------------ /// Save a row made / changed on this device (the whole row: columns we don't show are kept /// by passing the row as read). `u` = its id: a natural one ("day:2026-10-20") or random. void put(String t, String u, Map data) { final clean = Map.of(data) ..remove('_u') ..remove('_h'); db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, _tick(), device, jsonEncode(clean)]); } /// Has another device seen this row as it is (it came from one, or went out)? bool known(String t, String u) { final r = db.select('SELECT h, d FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; return r == null || r['d'] != device || (r['h'] as int) <= meta('pushed'); } void delete(String t, String u) { final h = _tick(); db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]); db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, device]); } /// Drop rows of [t] whose JSON [field] is below [before] — here only, no delete marker (the other side /// keeps them): only rows another device made, or ours already sent. void dropOld(String t, String field, num before) => db.execute( "DELETE FROM rec WHERE t = ? AND json_extract(data, '\$.$field') < ? AND (d != ? OR h <= ?)", [t, before, device, meta('pushed')]); static String randomId() { final r = Random.secure(); return List.generate(16, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); } // ---- sync --------------------------------------------------------------------------------- /// This device's changes since the last push: (changes, mark) — markPushed(mark) once sent. (List>, int) changes() { final since = meta('pushed'); var mark = since; final out = >[]; final items = <(int, Map)>[]; for (final r in db.select('SELECT t, u, h, d, data FROM rec WHERE d = ? AND h > ?', [device, since])) { items.add((r['h'] as int, {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'row': jsonDecode(r['data'] as String)})); } for (final r in db.select('SELECT t, u, h, d FROM tomb WHERE d = ? AND h > ?', [device, since])) { items.add((r['h'] as int, {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'del': true})); } items.sort((a, b) => a.$1.compareTo(b.$1)); for (final (h, c) in items) { out.add(c); mark = max(mark, h); } return (out, mark); } void markPushed(int mark) => setMeta('pushed', max(meta('pushed'), mark)); /// Another device's changes → {applied, skipped}. Rows first, then the deletes (like syncdb). Map apply(List changes) { final stats = {'applied': 0, 'skipped': 0}; if (changes.isEmpty) return stats; db.execute('BEGIN IMMEDIATE'); try { var top = meta('clock'); for (final c in changes.cast>()) { top = max(top, c['h'] as int); } setMeta('clock', top); // the clock moves past what arrives for (final pass in [false, true]) { for (final c in changes.cast>()) { if ((c['del'] == true) != pass) continue; final t = c['t'] as String, u = c['u'] as String, h = c['h'] as int, d = c['d'] as String; if (skip.any(t.startsWith)) { stats['skipped'] = stats['skipped']! + 1; continue; } final cur = db.select('SELECT h, d, data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; final tomb = db.select('SELECT h, d FROM tomb WHERE t = ? AND u = ?', [t, u]).firstOrNull; if (pass) { if (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) { db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, d]); } if (cur != null && newer(h, d, cur['h'] as int, cur['d'] as String)) { db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]); stats['applied'] = stats['applied']! + 1; } else { stats['skipped'] = stats['skipped']! + 1; } } else { if (cur != null && forks.containsKey(t) && (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) && _fork(t, u, h, d, (c['row'] as Map).cast(), cur)) { stats['applied'] = stats['applied']! + 1; continue; } final beaten = (tomb != null && !newer(h, d, tomb['h'] as int, tomb['d'] as String)) || (cur != null && !newer(h, d, cur['h'] as int, cur['d'] as String)); if (beaten) { stats['skipped'] = stats['skipped']! + 1; } else { db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, h, d, jsonEncode(c['row'])]); stats['applied'] = stats['applied']! + 1; } } } } db.execute('COMMIT'); } catch (_) { db.execute('ROLLBACK'); rethrow; } return stats; } /// syncdb._fork: a document row meeting another version of itself → true when settled here, /// false = go on with the plain last-change-wins (after keeping the loser as a copy). bool _fork(String t, String u, int h, String d, Map row, Row cur) { final loc = jsonDecode(cur['data'] as String) as Map; final mine = loc['rev'] as String?, theirs = row['rev'] as String?; if (mine == null || theirs == null || mine == theirs) return false; // the same text: only the rest differs final win = newer(h, d, cur['h'] as int, cur['d'] as String); final text = [...forks[t]!, 'rev', 'revs']; List revs(Map m) => ((m['revs'] as String?) ?? '').split(' '); if (revs(row).contains(mine)) { // written on top of ours: its text if (win) return false; final merged = {...loc, for (final k in text) if (row.containsKey(k)) k: row[k]}; db.execute('UPDATE rec SET data = ? WHERE t = ? AND u = ?', [jsonEncode(merged), t, u]); return true; } if (revs(loc).contains(theirs)) { // ours was written on top of it: our text, their pin / folder — if (!win) return false; // stamped here, so it goes out (with their stamp our text never would) final merged = {...row, for (final k in text) if (loc.containsKey(k)) k: loc[k]}; db.execute('UPDATE rec SET h = ?, d = ?, data = ? WHERE t = ? AND u = ?', [_tick(), device, jsonEncode(merged), t, u]); return true; } // both written at the same time: the later one stays, the other becomes a copy (the same one on every device) final (lost, lh, ld) = win ? (loc, cur['h'] as int, cur['d'] as String) : (row, h, d); final cu = 'copy:${lost['rev']}'; if (db.select('SELECT 1 FROM rec WHERE t = ? AND u = ?', [t, cu]).isEmpty && db.select('SELECT 1 FROM tomb WHERE t = ? AND u = ?', [t, cu]).isEmpty) { db.execute('INSERT INTO rec VALUES (?, ?, ?, ?, ?)', [t, cu, lh, ld, jsonEncode({...lost, 'origin': lost['rev']})]); } return false; } }