-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.dart
More file actions
195 lines (170 loc) Β· 6.64 KB
/
example.dart
File metadata and controls
195 lines (170 loc) Β· 6.64 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
/// # dynos_sync β Complete Example
///
/// This example shows how to set up dynos_sync with Drift + Supabase
/// in a typical Flutter app.
// ignore_for_file: unused_local_variable
import 'package:dynos_sync/dynos_sync.dart';
// βββ Step 1: Define your Drift database βββββββββββββββββββββββββββββββββββββ
//
// Add DynosSyncQueueTable and DynosSyncTimestampsTable to your database:
//
// @DriftDatabase(tables: [
// TasksTable,
// NotesTable,
// DynosSyncQueueTable, // β add this
// DynosSyncTimestampsTable, // β add this
// ])
// class AppDatabase extends _$AppDatabase { ... }
// βββ Step 2: Create the sync engine (once at app start) βββββββββββββββββββββ
SyncEngine createSyncEngine({
required LocalStore local,
required RemoteStore remote,
required QueueStore queue,
required TimestampStore timestamps,
}) {
return SyncEngine(
local: local,
remote: remote,
queue: queue,
timestamps: timestamps,
tables: ['tasks', 'notes', 'categories'],
config: const SyncConfig(
batchSize: 50,
queueRetention: Duration(days: 30),
stopOnFirstError: true,
maxRetries: 3,
sensitiveFields: ['ssn', 'password'], // π‘οΈ [NEW] mask PII in error logs
useExponentialBackoff: true, // πΆ [NEW] 2, 4, 8s retry delay
),
onError: (error, stack, context) {
print('Sync error [$context]: $error');
},
);
}
// βββ Step 3: Usage patterns βββββββββββββββββββββββββββββββββββββββββββββββββ
/// Pattern A: Let dynos_sync handle both local write and sync
Future<void> createTask(SyncEngine sync, String id, String title) async {
await sync.write('tasks', id, {
'id': id,
'title': title,
'done': false,
'updated_at': DateTime.now().toUtc().toIso8601String(),
});
// Done! Written locally + queued for remote push.
}
/// Pattern B: Write to your own DAO, then push via dynos_sync
Future<void> createTaskViaDao(
SyncEngine sync, Map<String, dynamic> task) async {
// Your own DAO handles the local write:
// await db.taskDao.save(Task.fromJson(task));
// Then just queue the remote push:
await sync.push('tasks', task['id'] as String, task);
}
/// Pattern C: Partial update (patch) β only sends changed fields
Future<void> markTaskDone(SyncEngine sync, String id) async {
// Updates only these columns via UPDATE, not upsert.
// Avoids NOT NULL failures from missing columns.
await sync.push(
'tasks',
id,
{
'done': true,
'finished_at': DateTime.now().toUtc().toIso8601String(),
},
operation: SyncOperation.patch);
}
/// Pattern D: Delete a record
Future<void> deleteTask(SyncEngine sync, String id) async {
await sync.remove('tasks', id);
// Deleted locally + queued for remote deletion.
}
// βββ Step 4: App lifecycle ββββββββββββββββββββββββββββββββββββββββββββββββββ
/// Call on app launch (e.g., in splash screen)
Future<void> onAppLaunch(SyncEngine sync) async {
// This drains pending writes + pulls remote changes.
// First call: pulls everything. Subsequent calls: only what changed.
await sync.syncAll();
}
/// Call in splash screen to wait for data before showing home
Future<void> splashScreenWait(SyncEngine sync) async {
await sync.initialSyncDone;
// Safe to navigate to home β local DB is populated.
}
/// Call on pull-to-refresh
Future<void> onRefresh(SyncEngine sync) async {
await sync.drain();
await sync.pullAll();
}
// βββ Step 5: Session Termination ββββββββββββββββββββββββββββββββββββββββββββ
/// Call when the user logs out.
///
/// **CRITICAL SECURITY STEP:** This purges the local sync queue and resets
/// timestamps to ensure User A's data doesn't leak into User B's session.
Future<void> onUserLogout(SyncEngine sync) async {
await sync.logout();
}
// βββ Step 6: Runtime Table Registration ββββββββββββββββββββββββββββββββββββββ
/// Add tables to sync after engine is already running.
/// Useful for progressive consent or feature flags.
Future<void> registerNewTable(SyncEngine sync) async {
// Register and immediately pull remote data
await sync.addTable('categories');
// Register without pulling (will pull on next syncAll)
await sync.addTable('tags', pull: false);
// Stop syncing a table
sync.removeTable('deprecated_table');
}
// βββ Step 7: Background Isolate Offloading ββββββββββββββββββββββββββββββββββ
/// For massive datasets (10k+ rows), run the sync in a background isolate.
/// This ensures the primary UI thread remains silky smooth (60/120 FPS).
///
/// Pass a factory function that constructs the engine β Dart isolates cannot
/// share live database objects, so the engine is re-created inside the isolate.
Future<void> runHeavySync({
required LocalStore Function() localFactory,
required RemoteStore Function() remoteFactory,
required QueueStore Function() queueFactory,
required TimestampStore Function() timestampsFactory,
}) async {
final hardened = IsolateSyncEngine(
engineFactory: () => SyncEngine(
local: localFactory(),
remote: remoteFactory(),
queue: queueFactory(),
timestamps: timestampsFactory(),
tables: ['tasks', 'notes'],
),
);
await hardened.syncAllInBackground();
}
// βββ Full setup with Drift + Supabase βββββββββββββββββββββββββββββββββββββββ
//
// import 'package:dynos_sync_drift/dynos_sync_drift.dart';
// import 'package:dynos_sync_supabase/dynos_sync_supabase.dart';
//
// final db = AppDatabase();
// final client = Supabase.instance.client;
//
// final sync = SyncEngine(
// local: DriftLocalStore(db),
// remote: SupabaseRemoteStore(
// client: client,
// userId: client.auth.currentUser!.id,
// tableTimestampKeys: {
// 'tasks': 'tasks_at',
// 'notes': 'notes_at',
// 'categories': 'categories_at',
// },
// ),
// queue: DriftQueueStore(db),
// timestamps: DriftTimestampStore(db),
// tables: ['tasks', 'notes', 'categories'],
// );
//
// // In splash screen:
// await sync.syncAll();
// await sync.initialSyncDone;
// navigateToHome();
void main() {
print('See code comments for usage examples.');
}