computeAndScheduleDiff method
Compute diff vs baseline and schedule if non-empty. If empty, calls onNoDiff.
Implementation
void computeAndScheduleDiff(String id, String collectionName) {
final map = toSyncMapForId(id);
if (map == null) return;
final current = sanitize(map);
Map<String, dynamic> last = _lastSyncedById[id] ?? <String, dynamic>{};
Map<String, dynamic> patch = {};
// collectionType & userProvider are non-null by signature; always attempt cached diff first
final key = '$userId|${collectionName}|$id';
final dbCache = realm.find<SyncDBCache>(key);
if (dbCache != null) {
try {
final raw = jsonDecode(dbCache.diffJson) as Map<String, dynamic>;
patch = rehydratePatch(raw);
// Diff consumed: remove the cache entry so we don't resend stale patches after baseline update.
try {
realm.write(() {
realm.delete(dbCache);
});
} catch (e) {
AppLogger.log(
'SyncHelper: failed to delete consumed DBCache $key: $e',
);
}
} catch (e) {
// Malformed JSON in DBCache, fall back to computing diff
AppLogger.log(
'SyncHelper: malformed DBCache $key, recomputing diff: $e',
);
patch = diff(last, current);
// Clean up corrupted entry
try {
realm.write(() => realm.delete(dbCache));
} catch (_) {}
}
} else {
// Fallback to computing on the fly if cache not present
patch = diff(last, current);
}
// Create a check if there already same thing exists in queue or outbox patch and we dont overflow the queue
if (patch.isEmpty) {
if (onNoDiff != null) onNoDiff!(id);
return;
}
_schedule(id, patch);
}