Files
pipelines/app/lib/features/attention/runtime/attention_store.dart
T

83 lines
2.4 KiB
Dart

import 'package:shared_preferences/shared_preferences.dart';
import '../domain/attention_models.dart';
/// The persistence seam for the `Needs you` dismissal identities.
///
/// The controller only ever hands over the exact string produced by
/// [encodeAttentionDismissals], so a store cannot invent a different identity
/// format. Both directions are allowed to fail: a caller treats a null read as
/// "nothing dismissed yet" and a false write as "this session only".
abstract interface class AttentionStore {
Future<String?> read();
Future<bool> write(String value);
}
/// `shared_preferences` storage under the attention model's own key.
///
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
/// disk returns null/false instead of throwing into the caller's frame. Only the
/// documented [attentionStorageKey] is touched, never the legacy web key.
class SharedPreferencesAttentionStore implements AttentionStore {
const SharedPreferencesAttentionStore();
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String?> read() async {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(attentionStorageKey);
} catch (_) {
return null;
}
}
@override
Future<bool> write(String value) async {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(attentionStorageKey, value);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and isolated fixtures.
///
/// It never touches the platform store, so a probe or widget test cannot mutate
/// a real operator's persisted dismissals. [failReads] and [failWrites] reproduce
/// an unavailable store without throwing.
class MemoryAttentionStore implements AttentionStore {
MemoryAttentionStore({this.stored});
String? stored;
bool failReads = false;
bool failWrites = false;
int writes = 0;
@override
Future<String?> read() async {
if (failReads) throw StateError('attention store unavailable');
return stored;
}
@override
Future<bool> write(String value) async {
writes++;
if (failWrites) throw StateError('attention store is read-only');
stored = value;
return true;
}
}