This repository was archived by the owner on Sep 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase_sync_service.dart
More file actions
434 lines (385 loc) · 14.1 KB
/
Copy pathfirebase_sync_service.dart
File metadata and controls
434 lines (385 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// FirebaseSyncService for real-time synchronization between local SQLite and Firestore.
//
// Phase 5.2+: Real-Time Data Synchronization
//
// Responsibilities:
// - Provide a single integration point between the local SQLite storage (via DatabaseHelper)
// and Firebase Cloud Firestore.
// - Listen in real time to Firestore changes for user documents and mirror them locally.
// - Push local user changes to Firestore.
// - Implement deterministic, timestamp-based conflict resolution.
// - Expose a simple API for repositories/BLoCs to integrate without polluting UI code.
//
// Notes:
// - This implementation assumes that Firebase.initializeApp() is called in main.dart
// before using this service.
// - This file focuses on users; it is structured so Weeklies, Categories, etc. can be
// added following the same patterns.
// - Firestore security rules and authentication are assumed to be handled externally.
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../db/database_helper.dart';
import '../models/database_model.dart';
import '../models/user.dart';
/// A DTO wrapper describing the synchronization source of a change.
///
/// Useful if higher layers later want to distinguish between local-only,
/// remote-only, or merged updates.
enum SyncSource {
local,
remote,
merged,
}
/// Conflict resolution strategy:
///
/// - Firestore user documents and local users both carry a `updatedAt` timestamp
/// (stored as millisecondsSinceEpoch).
/// - On each incoming change (either local or remote), we compare timestamps:
/// - If remote.updatedAt > local.updatedAt => remote wins (apply remote locally).
/// - If local.updatedAt > remote.updatedAt => local wins (push local to remote).
/// - If equal => prefer remote for deterministic behavior.
///
/// To support this without modifying existing public User API, we:
/// - Store `updatedAt` in Firestore documents.
/// - Track `updatedAt` in a dedicated local metadata table keyed by userId.
/// - The repository can call [markUserLocallyUpdated] after local mutations so that
/// Firestore sync uses a coherent timestamp.
class FirebaseSyncService {
FirebaseSyncService._internal({
required DatabaseHelper dbHelper,
required FirebaseFirestore firestore,
}) : _dbHelper = dbHelper,
_firestore = firestore;
static FirebaseSyncService? _instance;
/// Initialize the global [FirebaseSyncService] singleton.
///
/// This must be called once (typically during app startup) after
/// `Firebase.initializeApp()` and before accessing [FirebaseSyncService.instance].
///
/// Safe to call multiple times; subsequent invocations return the existing instance.
static FirebaseSyncService init({
DatabaseHelper? dbHelper,
FirebaseFirestore? firestore,
}) {
_instance ??= FirebaseSyncService._internal(
dbHelper: dbHelper ?? DatabaseHelper.instance,
firestore: firestore ?? FirebaseFirestore.instance,
);
return _instance!;
}
/// Get the previously initialized [FirebaseSyncService] instance.
///
/// Throws:
/// - [StateError] if [init] has not been called.
static FirebaseSyncService get instance {
final inst = _instance;
if (inst == null) {
throw StateError(
'FirebaseSyncService not initialized. Call FirebaseSyncService.init() after Firebase.initializeApp().',
);
}
return inst;
}
final DatabaseHelper _dbHelper;
final FirebaseFirestore _firestore;
// =========================
// Firestore collection refs
// =========================
/// Firestore collection reference for `users`.
///
/// Exposed as a getter to keep collection naming centralized.
CollectionReference<Map<String, dynamic>> get _usersCollection =>
_firestore.collection('users');
// =========================
// Public API
// =========================
StreamSubscription<QuerySnapshot<Map<String, dynamic>>>?
_userListenerSubscription;
/// Start real-time synchronization for users.
///
/// - Subscribes to Firestore `users` collection.
/// - Applies remote changes into local SQLite using conflict resolution.
/// - Intended to be called once during app startup (after Firebase init).
Future<void> startUserRealtimeSync() async {
await _ensureSyncMetadataTable();
// Avoid duplicate listeners.
await _userListenerSubscription?.cancel();
_userListenerSubscription = _usersCollection.snapshots().listen(
(snapshot) async {
for (final change in snapshot.docChanges) {
final doc = change.doc;
final data = doc.data();
if (data == null) continue;
switch (change.type) {
case DocumentChangeType.added:
case DocumentChangeType.modified:
await _applyRemoteUserChange(doc.id, data);
break;
case DocumentChangeType.removed:
await _applyRemoteUserDeletion(doc.id);
break;
}
}
},
onError: (error, stackTrace) {
// In a production app, you might route this to a logger.
// Intentionally no rethrow here to avoid crashing listeners.
},
);
}
/// Stop listening for user real-time updates.
///
/// This cancels the active Firestore subscription, if any.
Future<void> stopUserRealtimeSync() async {
await _userListenerSubscription?.cancel();
_userListenerSubscription = null;
}
/// Push a locally created or updated [User] to Firestore.
///
/// Intended usage:
/// - Call after a successful local SQLite write for a given user.
///
/// Behavior:
/// - Uses a deterministic document id (`user_<id>`) so local/remote stay aligned.
/// - Attaches an `updatedAt` (millisecondsSinceEpoch) used for conflict resolution.
/// - Persists the same `updatedAt` into local sync metadata.
///
/// Returns:
/// - The `updatedAt` timestamp that was written.
///
/// Throws:
/// - [ArgumentError] if [user.id] is `null`.
Future<int> pushUserToRemote(User user) async {
if (user.id == null) {
throw ArgumentError(
'pushUserToRemote requires a persisted User with non-null id',
);
}
final updatedAt = DateTime.now().millisecondsSinceEpoch;
final docId = _userDocId(user.id!);
final payload = {
'id': user.id,
'name': user.name,
'email': user.email,
'password': user.password,
'updatedAt': updatedAt,
};
await _usersCollection.doc(docId).set(payload, SetOptions(merge: true));
await _setLocalUserUpdatedAt(user.id!, updatedAt);
return updatedAt;
}
/// Mark a local user as updated without immediately pushing to Firestore.
///
/// This is useful for batching strategies where you:
/// - Update SQLite,
/// - Record that the user changed (with a fresh `updatedAt`),
/// - Schedule a background sync to push all pending updates later.
///
/// Returns:
/// - The `updatedAt` timestamp recorded in local metadata.
Future<int> markUserLocallyUpdated(int userId) async {
final ts = DateTime.now().millisecondsSinceEpoch;
await _setLocalUserUpdatedAt(userId, ts);
return ts;
}
/// Delete a user in both local SQLite and Firestore.
///
/// Steps:
/// - Deletes the row from the local `users` table.
/// - Removes related metadata from the sync metadata table.
/// - Deletes the Firestore document with the deterministic id.
Future<void> deleteUserRemoteAndLocal(int userId) async {
final docId = _userDocId(userId);
await _dbHelper.runInTransaction((txn) async {
// Delete from local main User table.
await _dbHelper.delete(
table: UserTable.table,
where: '${UserTable.colId} = ?',
whereArgs: [userId],
txn: txn,
);
// Delete from sync metadata table.
await txn.delete(
_SyncMetadataTable.table,
where:
'${_SyncMetadataTable.colEntity} = ? AND ${_SyncMetadataTable.colEntityId} = ?',
whereArgs: [_SyncEntityType.user, userId],
);
});
// Delete from Firestore.
await _usersCollection.doc(docId).delete();
}
// =========================
// Internal helpers: users
// =========================
/// Apply a remote change for a user document into local SQLite.
///
/// Conflict resolution:
/// - Compares remote `updatedAt` vs local metadata `updated_at`.
/// - If remote is newer or local is missing: upserts local from remote.
/// - If local is newer: pushes local authoritative state back to Firestore.
///
/// Invalid or malformed documents (e.g. missing `id`) are ignored defensively.
Future<void> _applyRemoteUserChange(
String docId,
Map<String, dynamic> data,
) async {
final remoteId = data['id'];
if (remoteId is! int) {
// If id is missing or invalid, do not trust this document.
return;
}
final remoteUpdatedAt =
(data['updatedAt'] is int) ? data['updatedAt'] as int : 0;
final localMetaTs = await _getLocalUserUpdatedAt(remoteId);
if (remoteUpdatedAt >= localMetaTs) {
// Remote is authoritative; upsert into local DB.
final user = User(
id: remoteId,
name: (data['name'] ?? '') as String,
email: (data['email'] ?? '') as String,
password: (data['password'] ?? '') as String,
);
if (!user.isValid) return;
await _dbHelper.runInTransaction((txn) async {
final existing = await txn.query(
UserTable.table,
where: '${UserTable.colId} = ?',
whereArgs: [remoteId],
limit: 1,
);
if (existing.isEmpty) {
await txn.insert(
UserTable.table,
user.toMap(),
);
} else {
await txn.update(
UserTable.table,
user.toMap(),
where: '${UserTable.colId} = ?',
whereArgs: [remoteId],
);
}
await txn.insert(
_SyncMetadataTable.table,
{
_SyncMetadataTable.colEntity: _SyncEntityType.user,
_SyncMetadataTable.colEntityId: remoteId,
_SyncMetadataTable.colUpdatedAt: remoteUpdatedAt,
},
);
});
} else {
// Local is newer; push local authoritative state to Firestore.
final rows = await _dbHelper.query(
table: UserTable.table,
where: '${UserTable.colId} = ?',
whereArgs: [remoteId],
limit: 1,
);
if (rows.isEmpty) {
// Local deleted but remote exists and is older: prefer deletion.
await _usersCollection.doc(docId).delete();
return;
}
final localUser = User.fromMap(rows.first);
// Reuse the local metadata timestamp as authoritative.
final payload = {
'id': localUser.id,
'name': localUser.name,
'email': localUser.email,
'password': localUser.password,
'updatedAt': localMetaTs,
};
await _usersCollection.doc(docId).set(payload, SetOptions(merge: true));
}
}
/// Apply a remote deletion from Firestore to local state.
///
/// If a `users` document is removed remotely:
/// - Deletes the corresponding row from the local `users` table (when resolvable).
/// - Removes associated sync metadata entries.
Future<void> _applyRemoteUserDeletion(String docId) async {
final maybeId = _parseUserIdFromDocId(docId);
if (maybeId == null) return;
await _dbHelper.runInTransaction((txn) async {
await txn.delete(
UserTable.table,
where: '${UserTable.colId} = ?',
whereArgs: [maybeId],
);
await txn.delete(
_SyncMetadataTable.table,
where:
'${_SyncMetadataTable.colEntity} = ? AND ${_SyncMetadataTable.colEntityId} = ?',
whereArgs: [_SyncEntityType.user, maybeId],
);
});
}
String _userDocId(int userId) => 'user_$userId';
int? _parseUserIdFromDocId(String docId) {
if (!docId.startsWith('user_')) return null;
final idPart = docId.substring('user_'.length);
return int.tryParse(idPart);
}
// =========================
// Sync metadata management
// =========================
/// Ensure that the internal sync metadata table exists.
///
/// This table is used exclusively by [FirebaseSyncService] and related
/// infrastructure to track last-known update timestamps for entities.
Future<void> _ensureSyncMetadataTable() async {
// The DatabaseHelper currently exposes only high-level hooks; we use a
// one-time migration-style check here.
await _dbHelper.runInTransaction((txn) async {
await txn.execute('''
CREATE TABLE IF NOT EXISTS ${_SyncMetadataTable.table} (
${_SyncMetadataTable.colEntity} TEXT NOT NULL,
${_SyncMetadataTable.colEntityId} INTEGER NOT NULL,
${_SyncMetadataTable.colUpdatedAt} INTEGER NOT NULL,
PRIMARY KEY (${_SyncMetadataTable.colEntity}, ${_SyncMetadataTable.colEntityId})
);
''');
});
}
/// Read the last-known local `updated_at` value for [userId] from metadata.
///
/// Returns `0` when no record exists.
Future<int> _getLocalUserUpdatedAt(int userId) async {
final rows = await _dbHelper.query(
table: _SyncMetadataTable.table,
where:
'${_SyncMetadataTable.colEntity} = ? AND ${_SyncMetadataTable.colEntityId} = ?',
whereArgs: [_SyncEntityType.user, userId],
limit: 1,
);
if (rows.isEmpty) return 0;
final ts = rows.first[_SyncMetadataTable.colUpdatedAt];
if (ts is int) return ts;
return 0;
}
/// Persist or update the local `updated_at` value for [userId] in metadata.
Future<void> _setLocalUserUpdatedAt(int userId, int updatedAt) async {
await _dbHelper.insert(
table: _SyncMetadataTable.table,
values: {
_SyncMetadataTable.colEntity: _SyncEntityType.user,
_SyncMetadataTable.colEntityId: userId,
_SyncMetadataTable.colUpdatedAt: updatedAt,
},
);
}
}
/// Internal table definitions for sync metadata.
class _SyncMetadataTable {
static const String table = 'sync_metadata';
static const String colEntity = 'entity';
static const String colEntityId = 'entity_id';
static const String colUpdatedAt = 'updated_at';
}
/// Internal enum-like values for entities stored in sync metadata.
class _SyncEntityType {
static const String user = 'user';
}