Recipes

Offline edits and synchronization

Save a note with its outbox, recover lost acknowledgements and preserve local edits during versioned synchronization.

v1.2.2Beginnerark_data_layer

Full program: offline_sync_recipe.dart. This example edits one existing nonempty text note. It demonstrates both offline-first storage and explicit synchronization, not creation/deletion of a collection or a universal merge engine.

Part A: save locally before publishing

  1. load() reads the local note and its pending edits. Before load, data is null; editing or synchronization is rejected until local data has been loaded.
  2. save(text) validates the text and increments the local revision.
  3. One _NoteStore.update atomically stores the new note and an outbox entry. The entry contains the text, local revision and stable idempotency key.
  4. Only after local storage succeeds does the Repository publish _NoteData. The snapshot contains the current text, local/server revisions, pending count and a conflict indicator. Consumers never receive the mutable outbox itself.
  5. If local writing fails, neither data nor outbox changes and nothing is published. No network request is needed to save successfully.

The program closes and recreates the Repository over the same store and checks that the note and pending work are restored. That proves rehydration from the adapter, not persistence across a real process restart.

Part B: send and acknowledge one edit

  1. synchronize() captures the current local revision as its batch boundary. Await your save() before invoking sync if that edit must join this batch.
  2. The oldest pending edit receives an expected server version. This exact request is saved locally before network access, so a retry cannot change its key, payload or expected version after an ambiguous failure.
  3. The server checks the idempotency key and original payload. A repeat returns the prior receipt. Reusing the key with another payload is a protocol error. For a new key, the server checks the expected version before changing the note.
  4. The acknowledgement atomically removes only that edit and advances the locally known server version. It does not replace the latest local text with an older response. Local edits made during the network call remain queued.
  5. The next queued edit uses the acknowledged version. Edits newer than the batch boundary wait for the next explicit sync. There is no hidden retry worker.

Local read/modify/write/publication work is serialized inside the Repository; the network call is outside that queue. Consequently, saving a new local edit is not blocked behind a slow server request. Concurrent sync callers share a Future. Use one active Repository coordinator for this note; this is not an inter-isolate or multi-process lock.

Why the failure paths matter

  • No network: keep the prepared outbox entry and retry later.
  • Server applied the edit but its response was lost: keep the same entry. A recreated Repository retries it and receives the prior receipt without applying the edit twice.
  • Client could not save the acknowledgement: local work still remains queued. The same idempotent retry recovers the receipt without repeating the write.
  • Another device changed the server version: report _VersionConflict, keep local work and the remote version unchanged, and expose hasConflict. Do not silently discard a draft, overwrite the server or rebase an ambiguous request. Conflict resolution is a separate application action: obtain the authoritative remote note, ask the user to keep/merge/discard, and atomically record the chosen baseline and new operation. This example deliberately does not choose for them.

The conflict indicator is session state: recreating the Repository reloads the outbox, not a persisted conflict flag. A repeat sync rechecks the server version. The saved expected version still protects against an unintended overwrite.

What real adapters must guarantee

The in-memory store updates synchronously in one isolate. A real database adapter must provide an atomic transaction covering local data, revision counters, prepared request and outbox. A real server must commit the note change and its idempotency receipt atomically, scope keys by authenticated identity/resource, validate the entire payload, and retain receipts for its documented retry period. The fixed demo client ID is not a production identifier: persist a unique client ID and monotonic revision counter; do not reuse them for a fresh store.

The example makes no claim of exactly-once network delivery, durable storage, bounded outbox growth, encryption, authentication or background execution. These are adapter/application requirements, not features of Repository<Data>.

Repository implementation

The Repository below is taken from the runnable program linked above. That file also contains its domain types, imports, source adapters and executable checks; this excerpt is not a separate standalone program.

dart
final class _NoteRepository extends Repository<_NoteData?> {
  _NoteRepository({required super.dataSources})
    : _local = dataSources.get<_NoteStore>(),
      _remote = dataSources.get<_NoteServer>(),
      super(initialData: null);

  final _NoteStore _local;
  final _NoteServer _remote;
  Future<void> _localTail = Future<void>.value();
  Future<void>? _sync;

  Future<void> load() => _serialize<void>(() async {
    final _StoredNote stored = await _local.read();
    _publish(stored);
  });

  Future<void> save(final String text) => _serialize<void>(() async {
    _ensureLoaded();
    final String normalized = text.trim();
    if (normalized.isEmpty) throw ArgumentError.value(text, 'text');
    final _StoredNote stored = await _local.update((final _StoredNote current) {
      final int revision = current.localRevision + 1;
      final _PendingEdit edit = _PendingEdit(
        '${Uri.encodeComponent(current.clientId)}/$revision',
        revision,
        normalized,
      );
      return current.copyWith(
        text: normalized,
        localRevision: revision,
        pending: <_PendingEdit>[...current.pending, edit],
      );
    });
    _publish(stored);
  });

  Future<void> synchronize() {
    if (isClosed) throw RepositoryClosedException(runtimeType);
    _ensureLoaded();
    final Future<void>? existing = _sync;
    if (existing != null) return existing;
    final int throughRevision = data!.localRevision;
    final Future<void> operation = _sendThrough(
      throughRevision,
    ).whenComplete(() => _sync = null);
    _sync = operation;
    return operation;
  }

  Future<void> _sendThrough(final int throughRevision) async {
    while (!isClosed) {
      final _PendingEdit? edit = await _prepare(throughRevision);
      if (edit == null || isClosed) return;
      final _Receipt receipt;
      try {
        receipt = await _remote.apply(edit);
      } on _VersionConflict {
        if (!isClosed) {
          await _serialize<void>(() async {
            _publish(await _local.read(), hasConflict: true);
          });
        }
        rethrow;
      }
      if (isClosed) return;
      if (receipt.key != edit.key || receipt.version <= edit.expectedVersion!) {
        throw const _ProtocolFailure();
      }
      await _serialize<void>(() async {
        final _StoredNote stored = await _local.update((
          final _StoredNote current,
        ) {
          if (current.pending.isEmpty ||
              current.pending.first.key != edit.key) {
            throw const _ProtocolFailure();
          }
          // current.text may already belong to a newer local edit. Only the
          // acknowledged outbox entry is removed; the draft is not overwritten.
          return current.copyWith(
            serverVersion: receipt.version,
            pending: current.pending.skip(1),
          );
        });
        _publish(stored, hasConflict: false);
      });
    }
  }

  Future<_PendingEdit?> _prepare(final int throughRevision) =>
      _serialize<_PendingEdit?>(() async {
        final _StoredNote stored = await _local.update((
          final _StoredNote current,
        ) {
          if (current.pending.isEmpty ||
              current.pending.first.localRevision > throughRevision) {
            return current;
          }
          final _PendingEdit first = current.pending.first;
          if (first.expectedVersion != null) return current;
          // Persist the exact request BEFORE sending. A lost response must be
          // retried with the same key, payload and expected version.
          return current.copyWith(
            pending: <_PendingEdit>[
              first.withExpectedVersion(current.serverVersion),
              ...current.pending.skip(1),
            ],
          );
        });
        return stored.pending.isEmpty ||
                stored.pending.first.localRevision > throughRevision
            ? null
            : stored.pending.first;
      });

  Future<T> _serialize<T>(final Future<T> Function() action) {
    final Future<T> result = _localTail.then<T>((final void _) {
      if (isClosed) throw RepositoryClosedException(runtimeType);
      return action();
    });
    // Keep the internal queue usable after a failed write. The original result
    // still carries the error to its caller; this is not error suppression.
    _localTail = result.then<void>(
      (final T _) {},
      onError: (final Object error, final StackTrace stackTrace) {},
    );
    return result;
  }

  void _publish(final _StoredNote stored, {final bool? hasConflict}) {
    if (!isClosed) {
      setData(
        _NoteData(
          stored.text,
          stored.localRevision,
          stored.serverVersion,
          stored.pending.length,
          hasConflict: hasConflict ?? data?.hasConflict ?? false,
        ),
      );
    }
  }

  void _ensureLoaded() {
    if (data == null) {
      throw StateError('Load local data before editing or sync.');
    }
  }

  @override
  Future<void> closeRepository() => _localTail;
}

Closing and ownership in all recipes

Sources are constructed by the composition scope and resolved once through DataSourceContainer. Repositories never close those borrowed sources.

Closing invalidates later publication, not the underlying external operation. A network write may still take effect after the Repository closes. The sync example leaves the request in the outbox so the next coordinator can recover its receipt. A local transaction already in progress may still complete; queued work that has not started is rejected after close. Await outstanding operation Futures and handle their errors before closing the sources that serve them.

The pagination subscriber remains unpaused through close() to receive all committed states and done. In error cleanup it cancels its own subscription first. Do not infer that every foreign/paused subscription can always be drained by a deadline: see stream and lifecycle.

For additional subscription assertions, the published ark_data_layer_test companion observes a Repository without taking ownership. The examples here deliberately use only the runtime package and standard Dart libraries.