Compare commits

...

2 Commits

Author SHA1 Message Date
ea216d4a59 Sync pulls peers at once, off the UI thread
Some checks failed
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
dependency freshness / dependencies on newest stable (push) Has been cancelled
The board reported a 3.9 s sync.run spinner on the Pixel (todo:0c575b891b).
Eight ~2 MB peer logs were fetched, parsed on the UI isolate and merged one
by one, each merge rewriting the whole local store; a device without a
GitHub token still mirrored to GitHub (404s); settings and analytics waited
for the note sync.

Now changed peers download together, logs over 64 KB parse on an isolate
(inline on web), peers merge into one local write, the revision map and
listing share a round trip, the mirror is skipped without a token, and
settings/analytics run alongside the notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 11:25:22 +01:00
fafefabab6 MCP reads reuse a sync done within 2 s
A board fetch makes 15 MCP calls and each one synced with Firebase
(0.5-1 s), so a fetch took 12 s. Reads skip the sync when one ended
within readFreshness; writes always pull and push.

Todo: 475dc1d1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXu5EV5tPkCTEu6nxf
2026-11-19 11:17:50 +01:00
13 changed files with 543 additions and 67 deletions

View File

@ -8,6 +8,7 @@ import 'package:todo/data/note_repository.dart';
import 'package:todo/data/repo_note.dart';
import 'package:todo/mcp/board_client.dart';
import 'package:todo/mcp/task_split.dart';
import 'package:todo/sync/sync_service.dart';
/// The six task tools over one persistent sync node; calls run one at a time.
class TaskService {
@ -21,6 +22,7 @@ class TaskService {
this._session, {
this._board,
this.callTimeout = const Duration(seconds: 60),
this.readFreshness = const Duration(seconds: 2),
});
final CliSession _session;
@ -28,6 +30,13 @@ class TaskService {
/// Longest one call may run before it fails with a TimeoutException.
final Duration callTimeout;
/// How long a finished sync still counts for the read calls (list, search,
/// get). The board reads 15 times per fetch and each sync is a Firebase
/// round trip of 0.5-1 s, so reads inside the window skip it; every write
/// still pulls and pushes. [Duration.zero] syncs on every read.
final Duration readFreshness;
final Stopwatch _since = Stopwatch();
Future<void> _tail = Future.value();
Future<T> _serial<T>(Future<T> Function() body) {
@ -36,22 +45,34 @@ class TaskService {
return run;
}
Future<List<Note>> _pull() async {
final skipped = (await _session.sync(push: true)).skippedFiles;
if (skipped.isNotEmpty) throw StateError('sync: unmergeable $skipped');
Future<SyncResult> _sync() async {
final result = await _session.sync(push: true);
_since
..reset()
..start();
return result;
}
/// Pulls every peer, unless [read] and a sync ended within [readFreshness].
Future<List<Note>> _pull({bool read = false}) async {
final fresh = _since.isRunning && _since.elapsed < readFreshness;
if (!read || !fresh) {
final skipped = (await _sync()).skippedFiles;
if (skipped.isNotEmpty) throw StateError('sync: unmergeable $skipped');
}
return await _session.repository.listNotes();
}
Future<String> _save(Note note, String verb) async {
await _session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
await _session.sync(push: true);
await _sync();
return '$verb ${note.id}\n${listLine(note)}';
}
Future<Note> _find(_Args a) async {
Future<Note> _find(_Args a, {bool read = false}) async {
final id = a.required('id');
try {
return findNote(await _pull(), id);
return findNote(await _pull(read: read), id);
} on NoteLookupError catch (e) {
throw FormatException('id: $e');
}
@ -102,7 +123,7 @@ class TaskService {
final repo = a.repo();
final statuses = a.statuses();
final ideas = a.flag('no_repo');
await _pull();
await _pull(read: true);
final notes = await _session.repository.listNotes(
filter: NoteFilter(statuses: statuses, repo: repo, repoTasksOnly: !ideas),
);
@ -112,7 +133,7 @@ class TaskService {
/// `search_tasks`: repo tasks of any status whose text or repo matches.
Future<String> search(Map<String, dynamic> args) => _serial(() async {
final query = _Args(args).required('query');
await _pull();
await _pull(read: true);
return _lines(
await _session.repository.listNotes(
filter: NoteFilter(query: query, repoTasksOnly: true),
@ -122,7 +143,7 @@ class TaskService {
/// `get_task`: one note in full.
Future<String> get(Map<String, dynamic> args) =>
_serial(() async => noteDetail(await _find(_Args(args))));
_serial(() async => noteDetail(await _find(_Args(args), read: true)));
/// `update_task`: changes only the keys given; `done_check: ""` clears it.
Future<String> update(Map<String, dynamic> args) => _serial(() async {

7
lib/sync/off_thread.dart Normal file
View File

@ -0,0 +1,7 @@
/// Runs CPU-heavy, pure work away from the UI thread where the platform can.
///
/// Conditional export because `dart:isolate` does not run in a browser: the
/// web desktop build runs the work inline, everything else on a fresh isolate.
library;
export 'off_thread_io.dart' if (dart.library.js_interop) 'off_thread_web.dart';

View File

@ -0,0 +1,7 @@
import 'dart:isolate';
/// Runs [work] on a short-lived isolate and returns its result.
///
/// The result comes back through `Isolate.exit`, so a large parsed log is
/// handed over rather than copied.
Future<R> offThread<R>(R Function() work) => Isolate.run(work);

View File

@ -0,0 +1,2 @@
/// Runs [work] inline: a browser has no isolates for it.
Future<R> offThread<R>(R Function() work) async => work();

78
lib/sync/peer_pull.dart Normal file
View File

@ -0,0 +1,78 @@
/// Pulls the peers whose logs changed, all at once and off the UI thread.
///
/// Split out of `sync_service.dart` for file size. A peer's log is about
/// 2 MB; pulling eight of them one after another, each parsed on the UI
/// isolate, kept the phone's sync spinner up for 3.9 s (todo:0c575b891b).
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:todo/sync/off_thread.dart';
/// One peer file's pull result: its decoded [log] and revision, or a null
/// [log] when the file vanished, failed decryption or did not parse.
typedef PulledPeer = ({String name, String peer, Log? log, String? rev});
/// Fetches [names] (file names under [dir]) concurrently.
///
/// [knownRevs] holds each peer's published revision; a peer without one gets
/// its revision computed from the downloaded text. Any failure other than an
/// [E2eDecryptError] fails the pull, exactly as a sequential loop would.
Future<List<PulledPeer>> pullPeers(
RemoteStore remote,
String dir,
List<String> names,
Map<String, String> knownRevs,
) => Future.wait([
for (final name in names) _pull(remote, dir, name, knownRevs[peerOf(name)]),
], eagerError: true);
/// Peer id of a `<peer>.json` file name.
String peerOf(String name) =>
name.endsWith('.json') ? name.substring(0, name.length - 5) : name;
Future<PulledPeer> _pull(
RemoteStore remote,
String dir,
String name,
String? knownRev,
) async {
final peer = peerOf(name);
final String? text;
try {
text = await remote.getFileText('$dir/$name');
} on E2eDecryptError {
// Wrong key, tampered blob or a newer format: skipped and reported,
// never merged and never fatal.
return (name: name, peer: peer, log: null, rev: null);
}
if (text == null) return (name: name, peer: peer, log: null, rev: null);
final (log, rev) = await _decodeOffThread(text, knownRev);
return (name: name, peer: peer, log: log, rev: rev);
}
/// Below this many characters a log parses faster than an isolate starts.
const int _offThreadMinLength = 64 * 1024;
/// Kept separate so the isolate closure captures only [text] and [knownRev].
Future<(Log?, String)> _decodeOffThread(String text, String? knownRev) async {
(Log?, String) decode() => (decodeLog(text), knownRev ?? revisionOf(text));
return text.length < _offThreadMinLength ? decode() : await offThread(decode);
}
/// Parses a remote note log, returning `null` for a corrupt or wrong-shape
/// payload so one bad device file never aborts the whole sync.
Log? decodeLog(String text) {
try {
return logFromJson(text);
} on FormatException {
return null;
}
// crdt_sync's logFromJson throws a raw TypeError (not a custom
// exception) for a wrong-shape JSON payload from an untrusted peer
// file; must be caught too so one bad device file never aborts the
// whole sync (see doc comment above).
// ignore: avoid_catching_errors
on TypeError {
return null;
}
}

View File

@ -88,9 +88,13 @@ Future<SyncRunResult> runSync(
stateStore: stateStore ?? await openSyncStateStore(),
// coverage:ignore-end
);
final backend = firebase == null
? github
: MirrorStore(primary: firebase, mirror: github);
// No GitHub token means nothing to mirror: an unconfigured client still
// spends two round trips per call on 404s.
final backend = switch (firebase) {
null => github,
_ when !settings.isConfigured => firebase,
_ => MirrorStore(primary: firebase, mirror: github),
};
final e2e = await openEncryptedStore(
store: backend,
oldPrefix: service.notesDir,
@ -106,15 +110,26 @@ Future<SyncRunResult> runSync(
);
}
final layout = E2eLayout.of(service.notesDir);
final result = await SyncService(
// Settings and analytics touch other Firebase paths than the notes, so
// they ride alongside the note sync instead of after it.
final reconciled = appSettings?.reconcileWithRemote(firebase);
final flushed = analytics?.flush(firebase);
final notes = SyncService(
notesDir: layout.prefix,
revsPath: layout.revsPath,
stateStore: service.stateStore,
).sync(repository, e2e.store);
await analytics?.flush(firebase);
final done = await Future.wait<Object?>([
notes,
?reconciled,
?flushed,
// Not eager: the clients are closed below, so nothing may still be in
// flight when this returns or throws.
]);
final result = done.first! as SyncResult;
return SyncRunResult(
syncResult: result.withFirebaseConnected(value: firebase != null),
appSettings: await appSettings?.reconcileWithRemote(firebase),
appSettings: await reconciled,
);
} finally {
// Close both: unlike the long-lived desktop callers, each screen builds

View File

@ -1,6 +1,7 @@
import 'package:crdt_sync/crdt_sync.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/peer_pull.dart';
/// Outcome of a sync run, for surfacing in the UI.
class SyncResult {
@ -113,53 +114,61 @@ class SyncService {
final ownFileName = '$nodeId.json';
final state = await stateStore?.load() ?? const SyncState();
final remoteRevs = stateStore == null
? const <String, String>{}
: await _revisions(remote);
// Independent reads, so one round trip instead of two. eagerError keeps
// the first failure's own type, which callers catch.
final reads = await Future.wait<Object>([
if (stateStore == null)
Future.value(const <String, String>{})
else
_revisions(remote),
remote.listDirectory(notesDir),
], eagerError: true);
final remoteRevs = reads[0] as Map<String, String>;
final names = reads[1] as List<String>;
final seenRevs = <String, String>{};
// 1. Pull: list all device log files, merge everyone else's.
final names = await remote.listDirectory(notesDir);
var merged = 0;
// 1. Pull: every other device's log that changed since we merged it.
var skippedUnchanged = 0;
final skipped = <String>[];
final changed = <String>[];
for (final name in names) {
if (name == ownFileName) continue; // our own file; skip it.
final peer = name.endsWith('.json')
? name.substring(0, name.length - 5)
: name;
final peer = peerOf(name);
final remoteRev = remoteRevs[peer];
if (remoteRev != null && remoteRev == state.peerRevs[peer]) {
// Unchanged since we last merged it, and that merge is already in the
// local log — so the ~150 KB download is pure waste. Carry the
// revision forward so it stays skipped next time.
// local log -- so the download is pure waste. Carry the revision
// forward so it stays skipped next time.
seenRevs[peer] = remoteRev;
skippedUnchanged++;
continue;
}
final String? text;
try {
text = await remote.getFileText('$notesDir/$name');
} on E2eDecryptError {
// Wrong key, tampered blob or a newer format: skipped and reported,
// never merged and never fatal.
skipped.add(name);
changed.add(name);
}
var merged = 0;
final skipped = <String>[];
Log? incoming;
for (final pulled in await pullPeers(
remote,
notesDir,
changed,
remoteRevs,
)) {
final log = pulled.log;
if (log == null) {
// A vanished, undecryptable or undecodable peer file must not abort
// the sync, but it must not vanish silently either -- that's how a
// device drops out of sync unnoticed. Reported, and deliberately not
// recorded as seen: a corrupt push must be retried next run.
skipped.add(pulled.name);
continue;
}
final remoteLog = text == null ? null : _decodeLog(text);
if (remoteLog == null) {
// A vanished or undecodable peer file must not abort the sync, but
// it must not vanish silently either — that's how a device drops
// out of sync unnoticed. Report it in the result instead.
// Deliberately not recorded as seen: a corrupt push must be retried
// next run, not remembered as merged.
skipped.add(name);
continue;
}
await repo.importLog(remoteLog);
seenRevs[peer] = remoteRev ?? revisionOf(text!);
// Peers merge with each other first (commutative, idempotent), so the
// local store is rewritten once rather than once per peer.
incoming = incoming == null ? log : mergeLogs(incoming, log);
seenRevs[pulled.peer] = pulled.rev!;
merged++;
}
if (incoming != null) await repo.importLog(incoming);
// 2. Push: upload our own (now-merged) log under our node id.
// putFileText resolves our file's current sha itself.
@ -206,22 +215,4 @@ class SyncService {
if (remote is! BulkMapReader) return const {};
return await (remote as BulkMapReader).getStringMap(revsDir);
}
/// Parses a remote note log, returning `null` for a corrupt or wrong-shape
/// payload so one bad device file never aborts the whole sync.
Log? _decodeLog(String text) {
try {
return logFromJson(text);
} on FormatException {
return null;
}
// crdt_sync's logFromJson throws a raw TypeError (not a custom
// exception) for a wrong-shape JSON payload from an untrusted peer
// file; must be caught too so one bad device file never aborts the
// whole sync (see doc comment above).
// ignore: avoid_catching_errors
on TypeError {
return null;
}
}
}

View File

@ -23,6 +23,10 @@ task (`id8 status priority repo title created_by`); `get_task` prints
| Log, node id, session copy (0600) | `~/.local/share/todo-mcp/` |
| Binary | `~/.local/lib/todo-mcp/todo_mcp` |
Reads (`list_tasks`, `search_tasks`, `get_task`) reuse a Firebase sync that finished within
the last 2 s (`TaskService.readFreshness`); every write pulls and pushes. One board fetch
makes about 15 calls, each used to be a 0.5-1 s sync.
## One-time setup
```bash

View File

@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.98+1
version: 1.0.99+1
environment:
sdk: ^3.12.2

View File

@ -19,9 +19,12 @@ import '../cli/fake_rtdb.dart';
class McpHarness {
/// [board] is the fake board `new_note` talks to; none by default.
McpHarness({this.board});
/// [readFreshness] defaults to zero so every read syncs, as a test expects;
/// `task_service_fresh_test.dart` covers the production window.
McpHarness({this.board, this.readFreshness = Duration.zero});
final BoardClient? board;
final Duration readFreshness;
static const token = 'test-token-for-pc';
final Directory tmp = Directory.systemTemp.createTempSync('mcp_harness');
@ -39,7 +42,7 @@ class McpHarness {
httpClient: db.client,
);
server = await TodoMcpServer.start(
tasks: TaskService(session, board: board),
tasks: TaskService(session, board: board, readFreshness: readFreshness),
tokens: tokens,
port: 0,
);

View File

@ -0,0 +1,87 @@
// A read call (list/search/get) used to sync with Firebase every time, so the
// board's one fetch of 15 calls took 12 s and a note added in the app showed
// up 10-40 s later. Reads now reuse a sync that finished within
// `readFreshness`; every write still pulls and pushes.
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:todo/cli/cli_session.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/mcp/task_service.dart';
import 'package:todo/sync/sync_service.dart';
/// Counts [sync] calls; each one answers at once.
class _Counting extends CliSession {
_Counting(NoteRepository repo, FirebaseRestClient firebase)
: super('unused', repo, firebase);
int syncs = 0;
@override
Future<SyncResult> sync({required bool push}) {
syncs++;
return Future.value(const SyncResult(mergedDevices: 0, pushed: false));
}
}
Future<_Counting> _session() async {
final firebase = FirebaseRestClient(
databaseUrl: 'https://example.test',
auth: FirebaseTokenProvider(
apiKey: 'k',
store: InMemoryCredentialStore(
FirebaseCredentials(
idToken: 'id',
refreshToken: 'rt',
expiresAt: DateTime.utc(2099),
),
),
),
httpClient: http.Client(),
);
return _Counting(await NoteRepository.openInMemory(), firebase);
}
void main() {
const window = Duration(milliseconds: 300);
late _Counting session;
late TaskService tasks;
setUp(() async {
session = await _session();
tasks = TaskService(session, readFreshness: window);
});
test('[T-fresh] reads inside the window share one sync', () async {
await tasks.list({});
await tasks.list({'no_repo': true});
await tasks.search({'query': 'x'});
expect(session.syncs, 1);
});
test('[T-fresh] a read after the window syncs again', () async {
await tasks.list({});
await Future<void>.delayed(window + const Duration(milliseconds: 100));
await tasks.list({});
expect(session.syncs, 2);
});
test(
'[T-fresh] a write always syncs, and counts as fresh for reads',
() async {
await tasks.list({});
await tasks.add({'repo': 'kuhyx/x', 'title': 'a task'});
final afterAdd = session.syncs;
expect(afterAdd, greaterThan(1));
await tasks.list({});
expect(session.syncs, afterAdd);
},
);
test('[T-fresh] a zero window keeps the old sync-every-read', () async {
final strict = TaskService(session, readFreshness: Duration.zero);
await strict.list({});
await strict.list({});
expect(session.syncs, 2);
});
}

View File

@ -0,0 +1,105 @@
/// The sync spinner must clear in under a second on a phone link.
///
/// Every request to either backend waits [_rtt], a mobile round trip, so the
/// elapsed time measures how many round trips sit on the critical path. The
/// board reported a 3.9 s `sync.run` on the Pixel (todo:0c575b891b).
@TestOn('vm')
library;
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todo/data/app_settings.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/run_sync.dart';
import 'package:todo/sync/sync_settings.dart';
import 'fake_secure_storage.dart';
const _rtt = Duration(milliseconds: 150);
/// Firebase RTDB stand-in: a path-keyed JSON store behind a slow link.
class _SlowFirebase {
final data = <String, Object?>{};
final requests = <String>[];
http.Client client() => http_testing.MockClient((request) async {
requests.add('${request.method} ${request.url.path}');
await Future<void>.delayed(_rtt);
final key = request.url.path;
if (request.method == 'PUT') {
data[key] = jsonDecode(request.body);
return http.Response(request.body, 200);
}
if (request.method == 'PATCH') return http.Response(request.body, 200);
return http.Response(jsonEncode(data[key]), 200);
});
}
FirebaseRestClient _firebase(_SlowFirebase fake) => FirebaseRestClient(
databaseUrl: 'https://x-rtdb.europe-west1.firebasedatabase.app',
auth: FirebaseTokenProvider(
apiKey: 'AIzaKey',
store: InMemoryCredentialStore(
FirebaseCredentials(
idToken: 'id',
refreshToken: 'refresh',
expiresAt: DateTime.now().add(const Duration(hours: 1)),
),
),
),
httpClient: fake.client(),
);
void main() {
late NoteRepository repo;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeSecureStorage();
SharedPreferences.setMockInitialValues({});
repo = await NoteRepository.openInMemory(nodeId: 'me');
});
tearDown(() async => repo.close());
test('a Firebase-only sync clears the spinner in under 1 s', () async {
// The phone's setup: Firebase signed in, no GitHub token.
final fake = _SlowFirebase();
final github = <String>[];
final githubClient = http_testing.MockClient((request) async {
github.add('${request.method} ${request.url.path}');
await Future<void>.delayed(_rtt);
return http.Response('', 404);
});
final state = InMemorySyncStateStore();
const none = SyncSettings(owner: '', repo: '', token: '');
Future<SyncRunResult> once() => runSync(
repo,
none,
appSettings: const AppSettings(advancedMode: true),
httpClient: githubClient,
firebaseFactory: () async => _firebase(fake),
stateStore: state,
);
await once(); // first run publishes the header and our log
fake.requests.clear();
github.clear();
final clock = Stopwatch()..start();
final result = await once();
clock.stop();
expect(result.syncResult.firebaseConnected, isTrue);
expect(github, isEmpty, reason: 'no GitHub token: nothing to mirror');
expect(
clock.elapsed,
lessThan(const Duration(seconds: 1)),
reason: 'firebase: ${fake.requests}',
);
});
}

View File

@ -0,0 +1,156 @@
/// The pull half must not scale with peers one after another.
///
/// The board reported a 3.9 s sync on the Pixel (todo:0c575b891b): eight
/// peers of about 2 MB each were fetched, decrypted, parsed and merged in
/// series, each merge rewriting the whole local store.
@TestOn('vm')
library;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/sync_service.dart';
import 'sync_service_fakes.dart';
/// A [FakeRemote] whose every call waits [delay] and tracks how many of
/// them are in flight at once.
class _SlowRemote extends FakeRemote {
_SlowRemote(super.files);
static const delay = Duration(milliseconds: 50);
int _inFlight = 0;
int maxInFlight = 0;
Future<T> _slow<T>(Future<T> Function() run) async {
_inFlight++;
if (_inFlight > maxInFlight) maxInFlight = _inFlight;
try {
await Future<void>.delayed(delay);
return await run();
} finally {
_inFlight--;
}
}
@override
Future<String?> getFileText(String path) =>
_slow(() => super.getFileText(path));
@override
Future<List<String>> listDirectory(String path) =>
_slow(() => super.listDirectory(path));
@override
Future<Map<String, String>> getStringMap(String path) =>
_slow(() => super.getStringMap(path));
}
/// A [FakeRemote] that cannot decrypt [undecryptable].
class _LockedPeerRemote extends FakeRemote {
_LockedPeerRemote(super.files, this.undecryptable);
final String undecryptable;
@override
Future<String?> getFileText(String path) async {
if (path.endsWith(undecryptable)) throw E2eDecryptError('wrong key');
return super.getFileText(path);
}
}
/// Counts writes to the local store.
class _CountingPersistence extends MemoryPersistence {
int writes = 0;
@override
Future<void> write(String text) {
writes++;
return super.write(text);
}
}
Future<Map<String, String>> _peers(int count) async {
final files = <String, String>{};
for (var i = 0; i < count; i++) {
final text = logToJson(await buildPeerLog(title: 'peer $i'));
files['todo-sync/notes/peer$i.json'] = text;
files['todo-sync/revs/peer$i'] = revisionOf(text);
}
return files;
}
void main() {
test('fetches changed peers and the revision map concurrently', () async {
final remote = _SlowRemote(await _peers(4));
final repo = await NoteRepository.openInMemory(nodeId: 'me');
addTearDown(repo.close);
final result = await SyncService(
stateStore: InMemorySyncStateStore(),
).sync(repo, remote);
expect(result.mergedDevices, 4);
expect(remote.maxInFlight, greaterThanOrEqualTo(4));
});
test('merges every changed peer with one local store write', () async {
final remote = FakeRemote(await _peers(3));
final persistence = _CountingPersistence();
final repo = await NoteRepository.openWith(
persistence: persistence,
nodeId: 'me',
);
addTearDown(repo.close);
persistence.writes = 0;
final result = await SyncService(
stateStore: InMemorySyncStateStore(),
).sync(repo, remote);
expect(result.mergedDevices, 3);
expect(persistence.writes, 1);
expect(await repo.listNotes(), hasLength(1)); // same id on every peer
});
test('still skips an undecodable peer and merges the rest', () async {
final files = await _peers(2);
files['todo-sync/notes/bad.json'] = '{not json';
final repo = await NoteRepository.openInMemory(nodeId: 'me');
addTearDown(repo.close);
final result = await SyncService(
stateStore: InMemorySyncStateStore(),
).sync(repo, FakeRemote(files));
expect(result.mergedDevices, 2);
expect(result.skippedFiles, ['bad.json']);
});
test('skips a peer it cannot decrypt and merges the rest', () async {
final repo = await NoteRepository.openInMemory(nodeId: 'me');
addTearDown(repo.close);
final result = await SyncService(
stateStore: InMemorySyncStateStore(),
).sync(repo, _LockedPeerRemote(await _peers(2), 'peer1.json'));
expect(result.mergedDevices, 1);
expect(result.skippedFiles, ['peer1.json']);
});
test('a phone-sized peer log decodes on a background isolate', () async {
// Over the inline threshold, so this runs the isolate path end to end.
final big = logToJson(await buildPeerLog(title: 'x' * 100000));
final repo = await NoteRepository.openInMemory(nodeId: 'me');
addTearDown(repo.close);
final result = await SyncService().sync(
repo,
FakeRemote({'todo-sync/notes/big.json': big}),
);
expect(result.mergedDevices, 1);
expect((await repo.listNotes()).single.text, 'x' * 100000);
});
}