LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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 365 lines 13.8 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'api.dart';
5 import 'offline_store.dart';
6 import 'plan_sync.dart' show newMutationId;
7
8 /// Private goal intent is persisted before delivery, scoped to API+account.
9 /// Acknowledgement and current server state are distinct on an old retry.
10 class LearningGoalSync {
11 LearningGoalSync(this.api, {OfflineStore? store})
12 : store = store ?? OfflineStore.forApi(api);
13 final HttpIdentityApi api;
14 final OfflineStore store;
15 static final _tails = <String, Future<void>>{};
16 static const _cache = 'learning_goals';
17 static const _meta = 'learning_goals_received';
18 static final _uuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$',
19 caseSensitive: false);
20 void _scope() {
21 if (api.cacheNamespace != store.scope) {
22 throw const ApiException(401, 'cache_scope_closed');
23 }
24 }
25
26 Future<T> _serial<T>(Future<T> Function() run) {
27 final previous = _tails[store.scope], release = Completer<void>();
28 _tails[store.scope] = release.future;
29 return (() async {
30 if (previous != null) await previous;
31 try {
32 _scope();
33 await store.readQueue();
34 _scope();
35 final result = await run();
36 _scope();
37 return result;
38 } finally {
39 if (identical(_tails[store.scope], release.future)) {
40 _tails.remove(store.scope);
41 }
42 release.complete();
43 }
44 })();
45 }
46
47 static bool _time(dynamic value) =>
48 value is String &&
49 RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
50 DateTime.tryParse(value) != null;
51 Map<String, dynamic> _goal(dynamic raw) {
52 if (raw is! Map ||
53 raw['id'] is! String ||
54 !_uuid.hasMatch(raw['id']) ||
55 raw['owner_user_id'] != api.currentUserId ||
56 raw['title'] is! String ||
57 (raw['title'] as String).trim().isEmpty ||
58 (raw['title'] as String).length > 240 ||
59 (raw['title'] as String).contains('\u0000') ||
60 (raw['target'] != null &&
61 (raw['target'] is! String ||
62 (raw['target'] as String).length > 1000 ||
63 (raw['target'] as String).contains('\u0000'))) ||
64 (raw['subject_id'] != null &&
65 (raw['subject_id'] is! String ||
66 !_uuid.hasMatch(raw['subject_id'] as String))) ||
67 raw['version'] is! int ||
68 raw['version'] < 1 ||
69 !['active', 'completed', 'archived'].contains(raw['status']) ||
70 !_time(raw['created_at']) ||
71 !_time(raw['updated_at']) ||
72 (raw['status'] == 'archived'
73 ? !_time(raw['archived_at'])
74 : raw['archived_at'] != null)) {
75 throw const ApiException(502, 'invalid_learning_goal');
76 }
77 return {...Map<String, dynamic>.from(raw), 'pending_sync': false};
78 }
79
80 Future<List<Map<String, dynamic>>> pending() async {
81 _scope();
82 final queue = await store.readQueue();
83 _scope();
84 return queue.where((m) => m['entityType'] == 'learning_goal').toList();
85 }
86
87 Future<Map<String, dynamic>> read() => _serial(() async {
88 var offline = false;
89 late List<Map<String, dynamic>> goals;
90 try {
91 final response = await api.requestJson('GET', '/v1/learning/goals');
92 _scope();
93 if (response['items'] is! List || !_time(response['fetchedAt'])) {
94 throw const ApiException(502, 'invalid_learning_goals');
95 }
96 goals = (response['items'] as List).map(_goal).toList();
97 if (goals.map((g) => g['id']).toSet().length != goals.length ||
98 goals.any((g) => g['status'] == 'archived')) {
99 throw const ApiException(502, 'invalid_learning_goals');
100 }
101 await store.writeList(_cache, goals);
102 await store.writeList(_meta, [
103 {'fetchedAt': response['fetchedAt']}
104 ]);
105 } catch (error) {
106 _scope();
107 if (error is ApiException && error.statusCode == 403) {
108 // A denied read must never fall back to yesterday's private list.
109 // Retain intent in the shared journal for explicit recovery.
110 await store.writeList(_cache, []);
111 await store.writeList(_meta, []);
112 _scope();
113 }
114 if (!isOfflineFailure(error)) rethrow;
115 goals = (await store.readList(_cache)).map(_goal).toList();
116 offline = true;
117 }
118 final byId = {
119 for (final g in goals) g['id']: Map<String, dynamic>.from(g)
120 };
121 final mutations = await pending();
122 for (final mutation in mutations) {
123 _validateMutation(mutation);
124 final body = Map<String, dynamic>.from(mutation['payload'] as Map);
125 final id = mutation['entityId'];
126 final previous = byId[id];
127 if (previous == null && mutation['operation'] != 'create') continue;
128 byId[id] = {
129 ...?previous,
130 'id': id,
131 'owner_user_id': api.currentUserId,
132 'title': body['title'] ?? previous?['title'],
133 'target': body.containsKey('target')
134 ? body['target']
135 : previous?['target'],
136 'status': body['status'] ?? previous?['status'] ?? 'active',
137 'version': body['expectedVersion'],
138 'pending_sync': true,
139 'pending_archive': mutation['operation'] == 'archive',
140 'queueStatus': mutation['queueStatus'],
141 };
142 }
143 final meta = await store.readList(_meta);
144 _scope();
145 final visible =
146 byId.values.where((g) => g['status'] != 'archived').toList();
147 final visibleIds = visible.map((g) => g['id']).toSet();
148 return {
149 'items': visible,
150 'offline': offline,
151 'fetchedAt': meta.firstOrNull?['fetchedAt'],
152 'pendingCount': mutations.length,
153 'unlistedPending': [
154 for (final mutation in mutations)
155 if (!visibleIds.contains(mutation['entityId']))
156 {
157 'id': mutation['entityId'],
158 'operation': mutation['operation'],
159 'queueStatus': mutation['queueStatus']
160 }
161 ]
162 };
163 });
164 Future<Map<String, dynamic>> create(
165 {required String title, String? target, String? subjectId}) {
166 final id = newMutationId();
167 return _mutate(id, 'create', {
168 'id': id,
169 'title': title,
170 'target': target,
171 'subjectId': subjectId,
172 'expectedVersion': 0
173 });
174 }
175
176 Future<Map<String, dynamic>> update(
177 String id, int version, Map<String, dynamic> changes) =>
178 _mutate(id, 'update', {...changes, 'expectedVersion': version});
179 Future<Map<String, dynamic>> archive(String id, int version) =>
180 _mutate(id, 'archive', {'expectedVersion': version});
181 Future<Map<String, dynamic>> _mutate(
182 String id, String operation, Map<String, dynamic> raw) {
183 id = id.toLowerCase();
184 final normalized = {...raw};
185 if (normalized['title'] is String) {
186 normalized['title'] = (normalized['title'] as String).trim();
187 }
188 if (normalized['target'] is String) {
189 final target = (normalized['target'] as String).trim();
190 normalized['target'] = target.isEmpty ? null : target;
191 }
192 if (normalized['subjectId'] is String) {
193 normalized['subjectId'] =
194 (normalized['subjectId'] as String).toLowerCase();
195 }
196 final body =
197 jsonDecode(jsonEncode({...normalized, 'mutationId': newMutationId()}))
198 as Map<String, dynamic>;
199 return _serial(() async {
200 _validateBody(id, operation, body);
201 if ((await pending()).any((m) => m['entityId'] == id)) {
202 throw const ApiException(409, 'goal_sync_pending');
203 }
204 final mutation = {
205 'id': body['mutationId'],
206 'entityId': id,
207 'entityType': 'learning_goal',
208 'operation': operation,
209 'expectedVersion': body['expectedVersion'],
210 'payload': body
211 };
212 await store.enqueue(mutation);
213 try {
214 return {'queued': false, 'goal': await _send(mutation)};
215 } catch (error) {
216 _scope();
217 if (!isOfflineFailure(error)) rethrow;
218 return {'queued': true, 'goalId': id};
219 }
220 });
221 }
222
223 void _validateBody(String id, String operation, Map body,
224 {String code = 'invalid_goal_input'}) {
225 final allowed = {
226 'mutationId',
227 'expectedVersion',
228 if (operation == 'create') 'id',
229 if (operation != 'archive') ...['title', 'target', 'subjectId', 'status'],
230 };
231 final version = body['expectedVersion'];
232 if (!_uuid.hasMatch(id) ||
233 !['create', 'update', 'archive'].contains(operation) ||
234 body.keys.any((key) => !allowed.contains(key)) ||
235 body['mutationId'] is! String ||
236 !_uuid.hasMatch(body['mutationId'] as String) ||
237 version is! int ||
238 version < 0 ||
239 version >= 2147483647 ||
240 (operation == 'create'
241 ? (version != 0 || body['id'] != id || !body.containsKey('title'))
242 : version == 0) ||
243 (operation == 'update' &&
244 !['title', 'target', 'subjectId', 'status']
245 .any(body.containsKey)) ||
246 (body.containsKey('title') &&
247 (body['title'] is! String ||
248 (body['title'] as String).trim().isEmpty ||
249 (body['title'] as String).length > 240 ||
250 (body['title'] as String).contains('\u0000'))) ||
251 (body['target'] != null &&
252 (body['target'] is! String ||
253 (body['target'] as String).length > 1000 ||
254 (body['target'] as String).contains('\u0000'))) ||
255 (body['subjectId'] != null &&
256 (body['subjectId'] is! String ||
257 !_uuid.hasMatch(body['subjectId'] as String))) ||
258 (body.containsKey('status') &&
259 !['active', 'completed'].contains(body['status']))) {
260 throw ApiException(400, code);
261 }
262 }
263
264 void _validateMutation(Map<String, dynamic> mutation) {
265 if (mutation['entityType'] != 'learning_goal' ||
266 mutation['entityId'] is! String ||
267 mutation['operation'] is! String ||
268 mutation['payload'] is! Map ||
269 mutation['payload']['mutationId'] != mutation['id'] ||
270 mutation['payload']['expectedVersion'] != mutation['expectedVersion']) {
271 throw const ApiException(422, 'invalid_goal_mutation');
272 }
273 _validateBody(mutation['entityId'] as String,
274 mutation['operation'] as String, mutation['payload'] as Map,
275 code: 'invalid_goal_mutation');
276 }
277
278 Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
279 _validateMutation(mutation);
280 final body = Map<String, dynamic>.from(mutation['payload'] as Map);
281 final id = mutation['entityId'], operation = mutation['operation'];
282 if (mutation['entityType'] != 'learning_goal' ||
283 !['create', 'update', 'archive'].contains(operation) ||
284 body['mutationId'] != mutation['id'] ||
285 id is! String ||
286 !_uuid.hasMatch(id) ||
287 body['expectedVersion'] is! int ||
288 body['expectedVersion'] != mutation['expectedVersion'] ||
289 (operation == 'create' &&
290 (body['id'] != id || body['expectedVersion'] != 0))) {
291 throw const ApiException(422, 'invalid_goal_mutation');
292 }
293 late Map<String, dynamic> response;
294 try {
295 response = await api.requestJson(
296 operation == 'create'
297 ? 'POST'
298 : operation == 'update'
299 ? 'PATCH'
300 : 'DELETE',
301 '/v1/learning/goals${operation == 'create' ? '' : '/$id'}',
302 body: body);
303 _scope();
304 } catch (error) {
305 _scope();
306 if (error is ApiException && error.statusCode == 403) {
307 await store.writeList(_cache, []);
308 await store.writeList(_meta, []);
309 _scope();
310 }
311 if (error is ApiException && error.statusCode == 409) {
312 await store.markQueued(mutation['id'] as String, 'conflict',
313 error: error.code);
314 }
315 rethrow;
316 }
317 final ack = response['acknowledgement'];
318 final goal = _goal(response['goal']);
319 if (goal['id'] != id ||
320 ack is! Map ||
321 ack['mutationId'] != mutation['id'] ||
322 ack['goalId'] != id ||
323 ack['operation'] != operation ||
324 ack['appliedVersion'] != body['expectedVersion'] + 1 ||
325 goal['version'] < ack['appliedVersion'] ||
326 !_time(ack['acceptedAt']) ||
327 !['accepted', 'already_applied'].contains(ack['status'])) {
328 throw const ApiException(502, 'invalid_goal_acknowledgement');
329 }
330 if (goal['version'] == ack['appliedVersion']) {
331 if ((operation == 'archive' && goal['status'] != 'archived') ||
332 ['title', 'target', 'subjectId', 'status'].any((key) =>
333 body.containsKey(key) &&
334 goal[key == 'subjectId' ? 'subject_id' : key] != body[key])) {
335 throw const ApiException(502, 'invalid_goal_acknowledgement');
336 }
337 }
338 await store.acknowledge(mutation['id'] as String,
339 item: goal, acceptedAt: ack['acceptedAt'] as String, cacheKey: _cache);
340 _scope();
341 return goal;
342 }
343
344 Future<void> flush() => _serial(() async {
345 for (final mutation in await pending()) {
346 if (mutation['queueStatus'] == 'conflict') {
347 throw const ApiException(409, 'goal_version_conflict');
348 }
349 await _send(mutation);
350 }
351 });
352 Future<void> useServer(String id) => _serial(() async {
353 final response = await api.requestJson('GET', '/v1/learning/goals/$id');
354 _scope();
355 final server = _goal(response);
356 if (server['id'] != id ||
357 (await store.readQueue()).any((m) =>
358 m['entityId'] == id && m['entityType'] != 'learning_goal')) {
359 throw const ApiException(409, 'sync_entity_collision');
360 }
361 await store.discardEntityChanges(id,
362 serverItem: server, cacheKey: _cache, entityType: 'learning_goal');
363 _scope();
364 });
365 }