LifeMate — Personal, Family & Learning Companion

fix/local-task-persistence
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 236 lines 7.99 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3 import 'dart:math';
4
5 import 'package:shared_preferences/shared_preferences.dart';
6
7 import 'api.dart';
8 import 'local_write_guard.dart';
9
10 /// One local runtime session: shared by all production stores in this isolate.
11 /// Native pending-write state also survives replacement of this Dart session.
12 class LocalDataSession {
13 final _guard = const LocalWriteGuard();
14 bool _uncertain = false;
15 // All instances share the writer lock: read/modify/write cannot lose a record.
16 Future<void>? _tail;
17
18 Future<void> _ensureAvailable() async {
19 if (!_uncertain) {
20 try {
21 _uncertain = await _guard.getBlocked();
22 } catch (_) {
23 _uncertain = true;
24 }
25 }
26 if (_uncertain) {
27 throw const ApiException(500, 'local_storage_restart_required');
28 }
29 }
30
31 Future<T> _run<T>(Future<T> Function() operation) {
32 final previous = _tail;
33 final release = Completer<void>();
34 _tail = release.future;
35 Future<T> run() async {
36 if (previous != null) await previous;
37 try {
38 await _ensureAvailable();
39 return await operation();
40 } finally {
41 // Don't retain a completed future and its caller's async zone forever.
42 if (identical(_tail, release.future)) _tail = null;
43 release.complete();
44 }
45 }
46
47 return run();
48 }
49 }
50
51 /// Device-only data for the explicitly separate, unauthenticated test entrypoint.
52 /// Never used as an authorization boundary or as a production sync cache.
53 class LocalDataStore {
54 LocalDataStore(
55 {required this.category,
56 required this.displayName,
57 LocalDataSession? session})
58 : session = session ?? _processSession;
59
60 final String category;
61 final String displayName;
62 static const key = 'lifeguide.local_data.v1';
63 static const categories = {'girl_minor', 'boy_minor', 'adult'};
64 static const themes = {'girl_pink', 'boy_blue', 'adult_blue'};
65 static const kinds = {
66 'task',
67 'assignment',
68 'exam',
69 'event',
70 'routine',
71 'goal',
72 'study_session'
73 };
74 static const statuses = {'planned', 'in_progress', 'completed', 'cancelled'};
75 static const priorities = {'low', 'normal', 'high', 'urgent'};
76 static final _processSession = LocalDataSession();
77 final LocalDataSession session;
78
79 Future<T> _locked<T>(Future<T> Function() operation) =>
80 session._run(operation);
81
82 static String newId() {
83 final random = Random.secure();
84 return List.generate(
85 16, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'))
86 .join();
87 }
88
89 static Map<String, dynamic> _copy(Map<String, dynamic> value) =>
90 jsonDecode(jsonEncode(value)) as Map<String, dynamic>;
91
92 static Map<String, dynamic> _decode(String raw) {
93 try {
94 final data = jsonDecode(raw) as Map<String, dynamic>;
95 final profile = data['profile'] as Map<String, dynamic>;
96 final items = data['items'] as List<dynamic>;
97 if (data['version'] != 1 ||
98 !categories.contains(profile['profile_category']) ||
99 profile['user_id'] is! String ||
100 (profile['user_id'] as String).isEmpty ||
101 profile['display_name'] is! String ||
102 (profile['display_name'] as String).trim().isEmpty ||
103 (profile['display_name'] as String).trim().length > 120 ||
104 !themes.contains(profile['theme_preference'])) {
105 throw const FormatException();
106 }
107 final ids = <String>{};
108 for (final rawItem in items) {
109 final item = rawItem as Map<String, dynamic>;
110 if (item['id'] is! String ||
111 (item['id'] as String).isEmpty ||
112 !ids.add(item['id'] as String) ||
113 item['owner_user_id'] != profile['user_id'] ||
114 item['title'] is! String ||
115 (item['title'] as String).trim().isEmpty ||
116 (item['title'] as String).trim().length > 240 ||
117 !kinds.contains(item['kind']) ||
118 !statuses.contains(item['status']) ||
119 !priorities.contains(item['priority']) ||
120 (item['notes'] != null &&
121 (item['notes'] is! String ||
122 (item['notes'] as String).length > 10000)) ||
123 item['visibility'] != 'private') {
124 throw const FormatException();
125 }
126 for (final field in ['starts_at', 'due_at']) {
127 if (item[field] != null &&
128 (item[field] is! String ||
129 DateTime.tryParse(item[field] as String) == null)) {
130 throw const FormatException();
131 }
132 }
133 final start = DateTime.tryParse(item['starts_at'] as String? ?? '');
134 final due = DateTime.tryParse(item['due_at'] as String? ?? '');
135 if (start != null && due != null && due.isBefore(start)) {
136 throw const FormatException();
137 }
138 }
139 return data;
140 } catch (_) {
141 throw const ApiException(500, 'local_data_corrupt');
142 }
143 }
144
145 static Future<SharedPreferencesAsync> _preferences() async {
146 try {
147 // Android default is transactional DataStore. No legacy native/Dart cache.
148 return SharedPreferencesAsync();
149 } catch (_) {
150 throw const ApiException(500, 'local_storage_failed');
151 }
152 }
153
154 static Future<String?> _raw(
155 SharedPreferencesAsync prefs, LocalDataSession session) async {
156 final String? raw;
157 try {
158 raw = await prefs.getString(key);
159 } catch (_) {
160 throw const ApiException(500, 'local_storage_failed');
161 }
162 // Another engine may begin/publish a native write while this read awaits.
163 await session._ensureAvailable();
164 return raw;
165 }
166
167 Future<void> _write(
168 SharedPreferencesAsync prefs, Map<String, dynamic> data) async {
169 final raw = jsonEncode(data);
170 // Prevalidation does not attempt native I/O and must not poison the session.
171 if (utf8.encode(raw).length > 1024 * 1024) {
172 throw const ApiException(500, 'local_storage_failed');
173 }
174 try {
175 // Ownership is native and is granted before any DataStore write is sent.
176 // Only this opaque token can clear the marker after confirmed success.
177 final token = await session._guard.beginWrite();
178 await prefs.setString(key, raw);
179 await session._guard.completeWrite(token);
180 } catch (_) {
181 // Even DataStore may have published a native cache before a rename error.
182 // Prevent later reads/writes from treating that uncertain value as durable.
183 session._uncertain = true;
184 throw const ApiException(500, 'local_storage_restart_required');
185 }
186 }
187
188 static Future<Map<String, dynamic>?> readSavedProfile() =>
189 _processSession._run(() async {
190 final prefs = await _preferences();
191 final raw = await _raw(prefs, _processSession);
192 if (raw == null) return null;
193 return _copy(_decode(raw)['profile'] as Map<String, dynamic>);
194 });
195
196 Future<Map<String, dynamic>> _load(String? raw) async {
197 if (raw != null) return _decode(raw);
198 if (!categories.contains(category) ||
199 displayName.trim().isEmpty ||
200 displayName.trim().length > 120) {
201 throw const ApiException(400, 'local_invalid_profile');
202 }
203 return {
204 'version': 1,
205 'profile': {
206 'user_id': newId(),
207 'profile_category': category,
208 'display_name': displayName.trim(),
209 'theme_preference': category == 'girl_minor'
210 ? 'girl_pink'
211 : category == 'boy_minor'
212 ? 'boy_blue'
213 : 'adult_blue',
214 },
215 'items': <Map<String, dynamic>>[],
216 };
217 }
218
219 Future<Map<String, dynamic>> read() => _locked(() async {
220 final prefs = await _preferences();
221 final raw = await _raw(prefs, session);
222 final missing = raw == null;
223 final data = await _load(raw);
224 if (missing) await _write(prefs, data);
225 return _copy(data);
226 });
227
228 Future<T> mutate<T>(T Function(Map<String, dynamic> data) change) =>
229 _locked(() async {
230 final prefs = await _preferences();
231 final data = await _load(await _raw(prefs, session));
232 final result = change(data);
233 await _write(prefs, data);
234 return result;
235 });
236 }