diff --git a/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md b/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md index f14a39ceec47..fff70c911544 100644 --- a/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md @@ -1,5 +1,9 @@ -## NEXT +## 2.4.2 +* Fixes `SharedPreferencesWindows` and `SharedPreferencesAsyncWindows` silently + deleting each other's preferences when an app uses both in one isolate. +* Recovers from a damaged `shared_preferences.json` instead of throwing, keeping + the preferences that can still be read. * Updates minimum supported SDK version to Flutter 3.38/Dart 3.10. ## 2.4.1 diff --git a/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart b/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart index 16d213904db9..ab688c7b0e00 100644 --- a/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart +++ b/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'dart:async'; -import 'dart:convert' show json; +import 'dart:convert' show json, utf8; import 'package:file/file.dart'; import 'package:file/local.dart'; @@ -48,12 +48,32 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { /// Checks for cached preferences and returns them or loads preferences from /// file and returns and caches them. Future> _readPreferences() async { - _cachedPreferences ??= await _readFromFile( + if (_cachedPreferences case final Map cached) { + return cached; + } + final Map read = await _readFromFile( + _defaultFileName, + fs: fs, + pathProvider: pathProvider, + ); + // A write that finished during the read has already cached newer data. + return _cachedPreferences ??= read; + } + + /// Applies [update] to the stored preferences and caches the result, + /// returning whether it was written. + Future _update(void Function(Map preferences) update) async { + final Map? preferences = await _updatePreferences( _defaultFileName, + update, fs: fs, pathProvider: pathProvider, ); - return _cachedPreferences!; + if (preferences == null) { + return false; + } + _cachedPreferences = preferences; + return true; } @override @@ -70,13 +90,13 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { Future clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; - final Map preferences = await _readPreferences(); - preferences.removeWhere( - (String key, _) => - key.startsWith(filter.prefix) && - (filter.allowList == null || filter.allowList!.contains(key)), + return _update( + (Map preferences) => preferences.removeWhere( + (String key, _) => + key.startsWith(filter.prefix) && + (filter.allowList == null || filter.allowList!.contains(key)), + ), ); - return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } @override @@ -103,17 +123,13 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { } @override - Future remove(String key) async { - final Map preferences = await _readPreferences(); - preferences.remove(key); - return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); + Future remove(String key) { + return _update((Map preferences) => preferences.remove(key)); } @override - Future setValue(String valueType, String key, Object value) async { - final Map preferences = await _readPreferences(); - preferences[key] = value; - return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); + Future setValue(String valueType, String key, Object value) { + return _update((Map preferences) => preferences[key] = value); } } @@ -205,18 +221,12 @@ base class SharedPreferencesAsyncWindows extends SharedPreferencesAsyncPlatform ClearPreferencesParameters parameters, SharedPreferencesOptions options, ) async { - final SharedPreferencesWindowsOptions windowsOptions = - SharedPreferencesWindowsOptions.fromSharedPreferencesOptions(options); final PreferencesFilters filter = parameters.filter; - final Map preferences = await _readPreferences(windowsOptions.fileName); - preferences.removeWhere( - (String key, _) => filter.allowList == null || filter.allowList!.contains(key), - ); - await _writePreferences( - preferences, - windowsOptions.fileName, - fs: fs, - pathProvider: pathProvider, + await _update( + options, + (Map preferences) => preferences.removeWhere( + (String key, _) => filter.allowList == null || filter.allowList!.contains(key), + ), ); } @@ -245,24 +255,42 @@ base class SharedPreferencesAsyncWindows extends SharedPreferencesAsyncPlatform return prefs; } - Future _setValue(String key, Object value, SharedPreferencesOptions options) async { + Future _setValue(String key, Object value, SharedPreferencesOptions options) { + return _update(options, (Map preferences) => preferences[key] = value); + } + + /// Applies [update] to the stored preferences and, if that was written, + /// caches the result. + Future _update( + SharedPreferencesOptions options, + void Function(Map preferences) update, + ) async { final SharedPreferencesWindowsOptions windowsOptions = SharedPreferencesWindowsOptions.fromSharedPreferencesOptions(options); - final Map preferences = await _readPreferences(windowsOptions.fileName); - preferences[key] = value; - await _writePreferences( - preferences, + final Map? preferences = await _updatePreferences( windowsOptions.fileName, + update, fs: fs, pathProvider: pathProvider, ); + if (preferences != null) { + _cachedPreferences = preferences; + } } /// Checks for cached preferences and returns them or loads preferences from /// file and returns and caches them. Future> _readPreferences(String fileName) async { - _cachedPreferences ??= await _readFromFile(fileName, fs: fs, pathProvider: pathProvider); - return _cachedPreferences!; + if (_cachedPreferences case final Map cached) { + return cached; + } + final Map read = await _readFromFile( + fileName, + fs: fs, + pathProvider: pathProvider, + ); + // A write that finished during the read has already cached newer data. + return _cachedPreferences ??= read; } } @@ -287,25 +315,98 @@ Future> _readFromFile( FileSystem fs = const LocalFileSystem(), PathProviderWindows? pathProvider, }) async { - var preferences = {}; final File? localDataFile = await _getLocalDataFile(fileName, fs: fs, pathProvider: pathProvider); - if (localDataFile != null && localDataFile.existsSync()) { - final String stringMap = localDataFile.readAsStringSync(); - if (stringMap.isNotEmpty) { - final Object? data = json.decode(stringMap); - if (data is Map) { - preferences = data.cast(); + return localDataFile == null ? {} : _readFile(localDataFile); +} + +/// Gets the preferences from an already-resolved file. +/// +/// Throws a [FileSystemException] if the file exists and still cannot be +/// opened after the retries. That is not read as empty, because a write that +/// started from empty would replace every stored key with just its own. +Future> _readFile(File localDataFile) async { + // A write empties the file and then fills it, so another process reading it + // in between sees it empty or cut off, or is refused the file altogether. + // Treating that as the stored data would make the next write here replace + // every key with just its own, so read again after a moment; the other write + // is long finished by then. Only a file whose contents stay unreadable, such + // as one a crash left half-written, reads as empty. + for (var attempt = 0; ; attempt++) { + final lastAttempt = attempt == _unreadableFileRetries; + try { + if (!localDataFile.existsSync()) { + return {}; + } + // Leniently: a damaged file can end part-way through a multi-byte character. + final String contents = utf8.decode(localDataFile.readAsBytesSync(), allowMalformed: true); + final Map? preferences = _decodePreferences(contents); + if (preferences != null) { + return preferences; + } + if (lastAttempt) { + debugPrint('Preferences file is unreadable; starting from empty.'); + return {}; + } + } on FileSystemException { + if (lastAttempt) { + rethrow; } } + await Future.delayed(_unreadableFileRetryDelay); } - return preferences; } -/// Writes the cached preferences to disk. Returns [true] if the operation -/// succeeded. -Future _writePreferences( - Map preferences, - String fileName, { +/// How many times [_readFile] reads an empty or unreadable file again. +const int _unreadableFileRetries = 5; + +/// The pause before each of those reads. +const Duration _unreadableFileRetryDelay = Duration(milliseconds: 20); + +/// Decodes the stored file's [contents], or returns null if they are empty or +/// cannot be read at all. +/// +/// Two processes writing the file at once, such as two instances of an app, +/// can leave one complete write followed by the tail of an older, longer one. +/// That leading write is still valid JSON and is kept, so the next write +/// replaces the damage. +Map? _decodePreferences(String contents) { + if (contents.isEmpty) { + return null; + } + Object? data; + try { + data = json.decode(contents); + } on FormatException catch (e) { + final int? offset = e.offset; + if (offset == null || offset <= 0 || offset >= contents.length) { + return null; + } + try { + data = json.decode(contents.substring(0, offset)); + } on FormatException { + return null; + } + debugPrint('Preferences file was damaged (${e.message}); kept its first $offset characters.'); + } + return data is Map ? data.cast() : {}; +} + +/// Applies [update] to what is currently stored in [fileName] and writes the +/// result back, returning the updated preferences, or null if the write failed. +/// +/// Both [SharedPreferencesWindows] and [SharedPreferencesAsyncWindows] store +/// their data in this one file, and a write replaces all of it, so a write has +/// to start from what is on disk now rather than from a map the calling store +/// read earlier -- otherwise it silently drops every key written since. +/// +/// Updates of the same file are queued and run one at a time, so within one +/// isolate concurrent writes, from either store, each see the previous one's +/// result. Nothing here coordinates with other isolates or other processes +/// writing the same file: their updates can still be lost to one made here at +/// the same moment, and the reverse. +Future?> _updatePreferences( + String fileName, + void Function(Map preferences) update, { FileSystem fs = const LocalFileSystem(), PathProviderWindows? pathProvider, }) async { @@ -317,18 +418,41 @@ Future _writePreferences( ); if (localDataFile == null) { debugPrint('Unable to determine where to write preferences.'); - return false; - } - if (!localDataFile.existsSync()) { - localDataFile.createSync(recursive: true); + return null; } - final String stringMap = json.encode(preferences); - localDataFile.writeAsStringSync(stringMap); + return await _queueUpdate(localDataFile.path, () async { + final Map preferences = await _readFile(localDataFile); + update(preferences); + if (!localDataFile.existsSync()) { + localDataFile.createSync(recursive: true); + } + localDataFile.writeAsStringSync(json.encode(preferences)); + return preferences; + }); } catch (e) { debugPrint('Error saving preferences to disk: $e'); - return false; + return null; } - return true; +} + +/// The last queued update of each file, by path, while any are pending. +final Map> _pendingUpdates = >{}; + +/// Runs [update] once every update of [filePath] queued before it has +/// finished, whether or not those succeeded. +Future _queueUpdate(String filePath, Future Function() update) { + final Future previous = _pendingUpdates[filePath] ?? Future.value(); + final Future result = previous.then((_) => update()); + // The queue only needs to know when this update is over, not how it went; + // the caller gets the error from [result]. + final Future done = result.then((_) {}, onError: (Object _) {}); + _pendingUpdates[filePath] = done; + done.whenComplete(() { + if (identical(_pendingUpdates[filePath], done)) { + _pendingUpdates.remove(filePath); + } + }); + return result; } /// Windows specific SharedPreferences Options. diff --git a/packages/shared_preferences/shared_preferences_windows/pubspec.yaml b/packages/shared_preferences/shared_preferences_windows/pubspec.yaml index 47d4834a7baa..1c25351322cd 100644 --- a/packages/shared_preferences/shared_preferences_windows/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_windows/pubspec.yaml @@ -2,7 +2,7 @@ name: shared_preferences_windows description: Windows implementation of shared_preferences repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 -version: 2.4.1 +version: 2.4.2 environment: sdk: ^3.10.0 diff --git a/packages/shared_preferences/shared_preferences_windows/test/shared_file_test.dart b/packages/shared_preferences/shared_preferences_windows/test/shared_file_test.dart new file mode 100644 index 000000000000..976db284f253 --- /dev/null +++ b/packages/shared_preferences/shared_preferences_windows/test/shared_file_test.dart @@ -0,0 +1,475 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; +import 'dart:io' as io; +import 'dart:typed_data'; + +import 'package:file/file.dart'; +import 'package:file/memory.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as path; +import 'package:path_provider_windows/path_provider_windows.dart'; +import 'package:shared_preferences_platform_interface/types.dart'; +import 'package:shared_preferences_windows/shared_preferences_windows.dart'; + +import 'fake_path_provider_windows.dart'; + +/// [SharedPreferencesWindows] and [SharedPreferencesAsyncWindows] store their +/// data in the same `shared_preferences.json`, and each write replaces the +/// whole file with that store's map. Neither may write a map it read before +/// the other store's writes, or those keys are silently lost. +void main() { + late MemoryFileSystem fs; + late PathProviderWindows pathProvider; + + const legacyKey = 'flutter.legacyString'; + const asyncKey = 'asyncString'; + const options = SharedPreferencesWindowsOptions(); + + setUp(() { + fs = MemoryFileSystem.test(); + pathProvider = FakePathProviderWindows(); + }); + + SharedPreferencesWindows getLegacyPreferences({ + FileSystem? fs_, + PathProviderWindows? pathProvider_, + }) { + final preferences = SharedPreferencesWindows(); + preferences.fs = fs_ ?? fs; + preferences.pathProvider = pathProvider_ ?? pathProvider; + return preferences; + } + + SharedPreferencesAsyncWindows getAsyncPreferences({ + FileSystem? fs_, + PathProviderWindows? pathProvider_, + }) { + final preferences = SharedPreferencesAsyncWindows(); + preferences.fs = fs_ ?? fs; + preferences.pathProvider = pathProvider_ ?? pathProvider; + return preferences; + } + + Future preferencesFile() async { + final String? directory = await pathProvider.getApplicationSupportPath(); + return fs.file(path.join(directory!, 'shared_preferences.json')); + } + + Future> readFile() async { + final File file = await preferencesFile(); + return json.decode(file.readAsStringSync()) as Map; + } + + Future writeFile(String contents) async { + final File file = await preferencesFile(); + file + ..createSync(recursive: true) + ..writeAsStringSync(contents); + } + + Future> getAllLegacy(SharedPreferencesWindows legacy) { + return legacy.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: 'flutter.')), + ); + } + + group('a damaged file', () { + // What two processes writing at once can leave: one complete write followed + // by the tail of an older, longer one. + const damagedFile = '{"$asyncKey":"kept","$legacyKey":"also kept"}7}'; + + test('keeps its complete leading write', () async { + await writeFile(damagedFile); + + expect(await getAsyncPreferences().getString(asyncKey, options), 'kept'); + expect(await getAllLegacy(getLegacyPreferences()), {legacyKey: 'also kept'}); + }); + + test('is repaired by a write', () async { + await writeFile(damagedFile); + + await getAsyncPreferences().setString('another', 'value', options); + + expect(await readFile(), { + asyncKey: 'kept', + legacyKey: 'also kept', + 'another': 'value', + }); + }); + + test('can end part-way through a character', () async { + final File file = await preferencesFile(); + file + ..createSync(recursive: true) + ..writeAsBytesSync([ + ...utf8.encode('{"$asyncKey":"café"}'), + // The second byte of a two-byte character, left over from a longer write. + 0xA9, + ...utf8.encode('"}'), + ]); + + expect(await getAsyncPreferences().getString(asyncKey, options), 'café'); + }); + + for (final (String description, String contents) in <(String, String)>[ + ('is cut off', '{"$asyncKey":"cut off'), + // The text before the error is not a complete write either. + ('has no complete leading write', '{"$asyncKey":"value",]'), + ('is not a JSON object', '["$asyncKey"]'), + ]) { + test('that $description reads as empty and is replaced by a write', () async { + await writeFile(contents); + + expect(await getAsyncPreferences().getString(asyncKey, options), isNull); + expect(await getLegacyPreferences().setValue('String', legacyKey, 'saved'), isTrue); + + expect(await readFile(), {legacyKey: 'saved'}); + }); + } + }); + + group('a file another process is writing', () { + const complete = '{"$asyncKey":"kept","$legacyKey":"also kept"}'; + + for (final (String description, Uint8List Function(Uint8List) firstRead) + in <(String, Uint8List Function(Uint8List))>[ + ('empty', (Uint8List bytes) => Uint8List(0)), + ('cut off', (Uint8List bytes) => Uint8List.sublistView(bytes, 0, bytes.length ~/ 2)), + ('locked', (Uint8List bytes) => throw const FileSystemException('The file is in use.')), + ]) { + test('is read again by a write when it is $description', () async { + await writeFile(complete); + final SharedPreferencesAsyncWindows preferences = getAsyncPreferences( + fs_: _FirstReadsFileSystem(fs, firstRead), + ); + + await preferences.setString('another', 'value', options); + + expect(await readFile(), { + asyncKey: 'kept', + legacyKey: 'also kept', + 'another': 'value', + }); + expect(await preferences.getString(asyncKey, options), 'kept'); + }); + + test('is read again by a first read when it is $description', () async { + await writeFile(complete); + final SharedPreferencesWindows legacy = getLegacyPreferences( + fs_: _FirstReadsFileSystem(fs, firstRead), + ); + + expect(await getAllLegacy(legacy), {legacyKey: 'also kept'}); + }); + } + + test('is left alone by a write when it stays locked', () async { + await writeFile(complete); + final lockedFs = _FirstReadsFileSystem( + fs, + (Uint8List bytes) => throw const FileSystemException('The file is in use.'), + count: 1000, + ); + + expect( + await getLegacyPreferences(fs_: lockedFs).setValue('String', 'flutter.another', 'value'), + isFalse, + ); + // The async store has no way to report the failure, but must not throw. + await getAsyncPreferences(fs_: lockedFs).setString('another', 'value', options); + + expect((await preferencesFile()).readAsStringSync(), complete); + }); + }); + + group('a write that fails', () { + test('because there is no support directory changes nothing', () async { + final noDirectory = _SupportPathProvider(() => null); + final SharedPreferencesWindows legacy = getLegacyPreferences(pathProvider_: noDirectory); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(pathProvider_: noDirectory); + + expect(await legacy.setValue('String', legacyKey, 'legacy value'), isFalse); + expect(await legacy.remove(legacyKey), isFalse); + expect(await legacy.clear(), isFalse); + await async.setString(asyncKey, 'async value', options); + + expect(await getAllLegacy(legacy), isEmpty); + expect(await async.getString(asyncKey, options), isNull); + expect((await preferencesFile()).existsSync(), isFalse); + }); + + test('because the support directory lookup throws returns false', () async { + final throwing = _SupportPathProvider(() => throw StateError('No support directory.')); + + expect( + await getLegacyPreferences( + pathProvider_: throwing, + ).setValue('String', legacyKey, 'legacy value'), + isFalse, + ); + await getAsyncPreferences( + pathProvider_: throwing, + ).setString(asyncKey, 'async value', options); + }); + + test('because the file cannot be written is not cached', () async { + await writeFile('{"$asyncKey":"stored","$legacyKey":"also stored"}'); + final readOnlyFs = _FailingWriteFileSystem(fs); + final SharedPreferencesWindows legacy = getLegacyPreferences(fs_: readOnlyFs); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(fs_: readOnlyFs); + + expect(await legacy.setValue('String', legacyKey, 'changed'), isFalse); + await async.setString(asyncKey, 'changed', options); + + expect(await getAllLegacy(legacy), {legacyKey: 'also stored'}); + expect(await async.getString(asyncKey, options), 'stored'); + }); + + test('does not hold up the writes queued behind it', () async { + final SharedPreferencesWindows failing = getLegacyPreferences( + fs_: _FailingWriteFileSystem(fs), + ); + final SharedPreferencesWindows legacy = getLegacyPreferences(); + + final List results = await Future.wait(>[ + failing.setValue('String', 'flutter.lost', 'value'), + legacy.setValue('String', legacyKey, 'legacy value'), + ]); + + expect(results, [false, true]); + expect(await readFile(), {legacyKey: 'legacy value'}); + }); + }); + + test('a legacy write keeps keys the async store wrote after it loaded', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + // Both stores load while the file is empty, as they do at app startup. + await getAllLegacy(legacy); + await async.getString(asyncKey, options); + + await async.setString(asyncKey, 'async value', options); + await legacy.setValue('String', legacyKey, 'legacy value'); + + expect(await readFile(), {asyncKey: 'async value', legacyKey: 'legacy value'}); + // Each store reads its own write back from its cache. + expect(await getAllLegacy(legacy), {legacyKey: 'legacy value'}); + expect(await async.getString(asyncKey, options), 'async value'); + }); + + test('an async write keeps keys the legacy store wrote after it loaded', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + await getAllLegacy(legacy); + await async.getString(asyncKey, options); + + await legacy.setValue('String', legacyKey, 'legacy value'); + await async.setString(asyncKey, 'async value', options); + + expect(await readFile(), {legacyKey: 'legacy value', asyncKey: 'async value'}); + expect(await getAllLegacy(legacy), {legacyKey: 'legacy value'}); + expect(await async.getString(asyncKey, options), 'async value'); + }); + + test('repeated interleaved writes keep both stores intact', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + for (var i = 0; i < 5; i++) { + await async.setInt('$asyncKey$i', i, options); + await legacy.setValue('int', '$legacyKey$i', i); + } + + final Map file = await readFile(); + final Map legacyValues = await getAllLegacy(legacy); + for (var i = 0; i < 5; i++) { + expect(file['$asyncKey$i'], i); + expect(file['$legacyKey$i'], i); + expect(await async.getInt('$asyncKey$i', options), i); + expect(legacyValues['$legacyKey$i'], i); + } + }); + + test('concurrent writes to both stores all land', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + // Nothing here awaits the previous write, which is what a fire-and-forget + // caller does: each read-modify-write has to be atomic against the others. + await Future.wait(>[ + async.setInt('${asyncKey}1', 1, options), + legacy.setValue('int', '${legacyKey}1', 1), + async.setInt('${asyncKey}2', 2, options), + legacy.setValue('int', '${legacyKey}2', 2), + ]); + + expect(await readFile(), { + '${asyncKey}1': 1, + '${legacyKey}1': 1, + '${asyncKey}2': 2, + '${legacyKey}2': 2, + }); + expect(await getAllLegacy(legacy), {'${legacyKey}1': 1, '${legacyKey}2': 2}); + expect(await async.getInt('${asyncKey}1', options), 1); + expect(await async.getInt('${asyncKey}2', options), 2); + }); + + test('concurrent writes all land while the file has to be read again', () async { + await writeFile('{"$asyncKey":"kept"}'); + // The first write's read yields to the event loop to retry, which is where + // the second write would get in if the two were not queued. + final retryingFs = _FirstReadsFileSystem(fs, (Uint8List bytes) => Uint8List(0)); + final SharedPreferencesWindows legacy = getLegacyPreferences(fs_: retryingFs); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + await Future.wait(>[ + legacy.setValue('String', legacyKey, 'legacy value'), + async.setString('another', 'value', options), + ]); + + expect(await readFile(), { + asyncKey: 'kept', + legacyKey: 'legacy value', + 'another': 'value', + }); + }); + + test('a legacy remove leaves the async store alone', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + await legacy.setValue('String', legacyKey, 'legacy value'); + await async.setString(asyncKey, 'async value', options); + await legacy.remove(legacyKey); + + expect(await readFile(), {asyncKey: 'async value'}); + expect(await getAllLegacy(legacy), isEmpty); + }); + + test('a legacy clear leaves the async store alone', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + // The legacy store's cache is filled before the async key exists. + await legacy.setValue('String', legacyKey, 'legacy value'); + await async.setString(asyncKey, 'async value', options); + await legacy.clear(); + + expect(await readFile(), {asyncKey: 'async value'}); + expect(await getAllLegacy(legacy), isEmpty); + }); + + test('an async clear leaves the legacy store alone', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + // The async store's cache is filled before the legacy key exists. + await async.setString(asyncKey, 'async value', options); + await legacy.setValue('String', legacyKey, 'legacy value'); + await async.clear( + const ClearPreferencesParameters(filter: PreferencesFilters(allowList: {asyncKey})), + options, + ); + + expect(await readFile(), {legacyKey: 'legacy value'}); + expect(await async.getString(asyncKey, options), isNull); + }); + + test('an async clear of everything removes keys the legacy store wrote', () async { + final SharedPreferencesWindows legacy = getLegacyPreferences(); + final SharedPreferencesAsyncWindows async = getAsyncPreferences(); + + await async.setString(asyncKey, 'async value', options); + await legacy.setValue('String', legacyKey, 'legacy value'); + await async.clear(const ClearPreferencesParameters(filter: PreferencesFilters()), options); + + expect(await readFile(), isEmpty); + expect( + await async.getKeys(const GetPreferencesParameters(filter: PreferencesFilters()), options), + isEmpty, + ); + }); +} + +/// A path provider with a replaceable application support path lookup. +class _SupportPathProvider extends FakePathProviderWindows { + _SupportPathProvider(this._supportPath); + + final String? Function() _supportPath; + + @override + Future getApplicationSupportPath() async => _supportPath(); +} + +/// A file system whose first [count] reads of a file's bytes go through +/// [firstRead], as if another process were part-way through writing the file. +class _FirstReadsFileSystem extends ForwardingFileSystem { + _FirstReadsFileSystem(super.delegate, this.firstRead, {this.count = 1}); + + final Uint8List Function(Uint8List bytes) firstRead; + final int count; + int _reads = 0; + + @override + File file(dynamic path) => _TestFile(delegate.file(path), onRead: _onRead); + + Uint8List _onRead(Uint8List bytes) => _reads++ < count ? firstRead(bytes) : bytes; +} + +/// A file system whose files cannot be written. +class _FailingWriteFileSystem extends ForwardingFileSystem { + _FailingWriteFileSystem(super.delegate); + + @override + File file(dynamic path) => _TestFile( + delegate.file(path), + onWrite: () => throw const FileSystemException('The disk is full.'), + ); +} + +class _TestFile extends ForwardingFileSystemEntity with ForwardingFile { + _TestFile(this.delegate, {this.onRead, this.onWrite}); + + @override + final File delegate; + + final Uint8List Function(Uint8List bytes)? onRead; + final void Function()? onWrite; + + @override + FileSystem get fileSystem => delegate.fileSystem; + + @override + Uint8List readAsBytesSync() { + final Uint8List bytes = delegate.readAsBytesSync(); + return onRead?.call(bytes) ?? bytes; + } + + @override + String readAsStringSync({Encoding encoding = utf8}) => encoding.decode(readAsBytesSync()); + + @override + void writeAsStringSync( + String contents, { + FileMode mode = FileMode.write, + Encoding encoding = utf8, + bool flush = false, + }) { + onWrite?.call(); + delegate.writeAsStringSync(contents, mode: mode, encoding: encoding, flush: flush); + } + + @override + File wrapFile(io.File delegate) => _TestFile(delegate as File, onRead: onRead, onWrite: onWrite); + + @override + Directory wrapDirectory(io.Directory delegate) => delegate as Directory; + + @override + Link wrapLink(io.Link delegate) => delegate as Link; +}