Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions lib/data/backup_extras.dart
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ class ImportSummary extends MapView<String, int> {
final List<String> refusedPrefs;
}

/// What a restore had committed when it stopped. Pass one to
/// [LocalDb.importFromDbFile] and read it in the catch: the thrown error is
/// unchanged, this only says how far the merge got. Rows are for tables that
/// finished; [days] counts days of a committed day_result page.
class RestoreProgress {
/// Table (or step) being worked on, so it names where a failure happened.
String phase = 'opening backup';
final Map<String, int> counts = {};
int days = 0;
/// Settings written / refused so far, kept if the settings step throws.
final keysWritten = <String>{};
final refusedPrefs = <String>[];
/// True once any page committed, i.e. a retry has rows to skip over.
bool committed = false;
int Function()? daysProbe;
int get rows => counts.entries
.where((e) => !e.key.startsWith('_'))
.fold(0, (a, e) => a + e.value);
}

/// The stored type of each backed-up key the app reads with a typed getter.
/// A row of another type is refused, not written: the getter throws on a cast
/// mismatch (int vs double included), on every launch after the restore. A
Expand Down Expand Up @@ -319,11 +339,12 @@ bool _needsServerReentry(String? saved) {

Future<ImportSummary> restoreBackupPrefs(String path, Map<String, int> counts, {
required bool freshInstall,
RestoreProgress? progress,
}) async {
final src = await openDatabase(path, readOnly: true, singleInstance: false);
try {
final written = <String>{};
final refused = <String>[];
final written = progress?.keysWritten ?? <String>{};
final refused = progress?.refusedPrefs ?? <String>[];
if (await _hasTable(src, 'backup_prefs')) {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
Expand Down
48 changes: 38 additions & 10 deletions lib/data/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12633,12 +12633,16 @@ class LocalDb {
/// renames on the way through is exactly the situation a restore has to
/// survive. Plain `.db` files (older backups, and `exportCopy` output) take
/// the same path they always did.
static Future<ImportSummary> importFromDbFile(String path) async {
///
/// [progress], when given, is filled as the merge runs so a caller that
/// catches an error can say how much was already committed.
static Future<ImportSummary> importFromDbFile(String path,
{RestoreProgress? progress}) async {
if (!await File(path).exists()) {
throw const FileSystemException('Backup file not found');
}
if (await sniffFile(path) != ImportContainer.gzip) {
return _restoreFromDbFile(path);
return _restoreFromDbFile(path, progress);
}
final work = await Directory.systemTemp.createTemp('openstrap_restore_');
try {
Expand All @@ -12649,7 +12653,7 @@ class LocalDb {
'That file unpacked to something that is not an OpenStrap database.',
);
}
return await _restoreFromDbFile(inflated);
return await _restoreFromDbFile(inflated, progress);
} finally {
// The inflated copy is a full second copy of the database, so it goes
// whether the import worked or not.
Expand Down Expand Up @@ -12691,7 +12695,8 @@ class LocalDb {
.single['populated'] == 0;
}

static Future<ImportSummary> _restoreFromDbFile(String path) async {
static Future<ImportSummary> _restoreFromDbFile(String path,
[RestoreProgress? progress]) async {
final db = await instance;
// Old database-only backups need no preference store. Inspect the copy
// before merge, which can make a new phone look established.
Expand All @@ -12718,8 +12723,11 @@ class LocalDb {
cancelled = prefs.getBool('alarm_schedule_cleared') == true;
}
final counts = await _mergeFromDbFile(path,
skip: cancelled ? const {'alarm_schedule'} : const {});
final summary = await restoreBackupPrefs(path, counts, freshInstall: fresh);
skip: cancelled ? const {'alarm_schedule'} : const {},
progress: progress);
progress?.phase = 'settings';
final summary = await restoreBackupPrefs(path, counts,
freshInstall: fresh, progress: progress);
// Persist only after settings restore succeeds, including a settings-only
// backup without an onboarding choice. A later restore keeps local edits.
if (hasSettings) await setCursor(_kSettingsImported, '1');
Expand Down Expand Up @@ -12946,6 +12954,11 @@ class LocalDb {
@visibleForTesting
static bool debugRowByRowMerge = false;

/// Test hook: runs inside every page's transaction of a restore, so a test
/// can throw after the Nth page.
@visibleForTesting
static Future<void> Function(Transaction txn)? debugBeforePageCommit;

@visibleForTesting
static Future<Map<String, int>> debugMergeRowByRow(String path) async {
final previous = debugRowByRowMerge;
Expand All @@ -12962,25 +12975,35 @@ class LocalDb {
List<String>? only,
bool tolerant = false,
Set<String> skip = const {},
}) => _withReaderInvalidated(() =>
_mergeFromDbFileImpl(path, only: only, tolerant: tolerant, skip: skip));
RestoreProgress? progress,
}) => _withReaderInvalidated(() => _mergeFromDbFileImpl(path,
only: only, tolerant: tolerant, skip: skip, progress: progress));

static Future<Map<String, int>> _mergeFromDbFileImpl(
String path, {
List<String>? only,
bool tolerant = false,
Set<String> skip = const {},
RestoreProgress? progress,
}) async {
var pageCommitted = false;
try {
return await _mergeFromDbFileBody(path,
only: only,
tolerant: tolerant,
skip: skip,
progress: progress,
beforePageCommit: (txn) async {
if (!pageCommitted) await _rotateStoreIdentity(txn);
await debugBeforePageCommit?.call(txn);
},
onPageCommitted: () {
pageCommitted = true;
if (progress != null) {
progress.committed = true;
progress.days = progress.daysProbe?.call() ?? progress.days;
}
},
onPageCommitted: () => pageCommitted = true,
);
} finally {
// A later page, source close or follow-up write can fail after a durable
Expand All @@ -13000,6 +13023,7 @@ class LocalDb {
required Future<void> Function(Transaction) beforePageCommit,
required void Function() onPageCommitted,
Set<String> skip = const {},
RestoreProgress? progress,
}) async {
final db = await instance;
final src = await openDatabase(path, readOnly: true);
Expand Down Expand Up @@ -13029,7 +13053,7 @@ class LocalDb {
return {for (final c in info) (c['name'] as String)};
}

final counts = <String, int>{};
final counts = progress?.counts ?? <String, int>{};
// DISTINCT DAYS ACTUALLY WRITTEN — the number the caller reports as
// "N days imported".
//
Expand All @@ -13042,6 +13066,7 @@ class LocalDb {
// null when day_result could not be read at all, so the caller can tell
// "nothing imported" from "we don't know".
Set<String>? importedDays;
progress?.daysProbe = () => importedDays?.length ?? 0;
List<String>? restoredWornOn;
// Days this device already finalized itself, read BEFORE anything merges.
// The day_result guard below protects their bundle; their series scalars,
Expand Down Expand Up @@ -13525,6 +13550,7 @@ class LocalDb {
: (srcEdge == null || localEdge > srcEdge ? localEdge : srcEdge);
}
for (final t in (only ?? tables)) {
progress?.phase = t;
if (skip.contains(t)) {
counts[t] = 0;
continue;
Expand Down Expand Up @@ -14115,6 +14141,7 @@ class LocalDb {
preserveError: failed,
);
}
progress?.phase = 'finishing';
if (counts.values.any((count) => count > 0)) {
await ActivityStore.suppressImportedAlerts(db);
}
Expand Down Expand Up @@ -14166,6 +14193,7 @@ class LocalDb {
// walks this map in order.
final days = importedDays;
if (days != null) counts['_days'] = days.length;
if (progress != null) progress.days = days?.length ?? progress.days;
// Archive buckets that could not be merged (a codec this build does not
// know) — kept out of the row counts, never silently.
if (archiveSkipped > 0) counts['_substrate_archive_skipped'] = archiveSkipped;
Expand Down
31 changes: 23 additions & 8 deletions lib/state/app_state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,8 @@ class AppState extends ChangeNotifier {
/// The days are in the database and the summaries built from them are not, so
/// reporting only the row count would claim a success the user does not have.
String? importRollupError;
/// Set when a restore committed some pages and then stopped.
String? lastImportPartial;

/// Days of stored raw history (substrate archive buckets) the last backup
/// import could NOT merge, because they are in a format this build does
Expand Down Expand Up @@ -823,15 +825,28 @@ class AppState extends ChangeNotifier {
// Invalidated however the import ends: it commits page by page, so a later
// page that throws can still leave merged calibration runs behind, and the
// refit can fail after a clean import. The cache holds runs, not profiles.
final ImportSummary counts;
lastImportPartial = null;
final progress = RestoreProgress();
ImportSummary counts;
try {
counts = await LocalDb.importFromDbFile(path);
} catch (_) {
// Nothing committed to report: the caller's zero-count error path.
invalidateLiveStepCalibration();
await _loadAlarmSchedule();
if (isConnected) await _armNextAlarmOccurrence();
rethrow;
counts = await LocalDb.importFromDbFile(path, progress: progress);
} catch (e) {
if (!progress.committed) {
// Nothing committed to report: the caller's zero-count error path.
invalidateLiveStepCalibration();
await _loadAlarmSchedule();
if (isConnected) await _armNextAlarmOccurrence();
rethrow;
}
// Some pages are already durable. Report them and carry on with the
// normal follow-up work instead of calling it a total failure.
lastImportPartial = 'restored ${progress.days} days '
'(${progress.rows} rows in finished tables), then stopped: '
'${progress.phase}: $e';
_log('[import] $lastImportPartial');
counts = ImportSummary({...progress.counts, '_days': progress.days},
keysWritten: progress.keysWritten,
refusedPrefs: progress.refusedPrefs);
}
// Rows are committed from here on. A later failure must not discard the
// day count, so it is surfaced through importRollupError instead.
Expand Down
2 changes: 2 additions & 0 deletions lib/ui2/onboarding/welcome.dart
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,8 @@ Future<ImportOutcome> runImport(
fileErrors.add('${nameOf(p)}: $e');
continue;
}
final partial = app.lastImportPartial;
if (partial != null) fileErrors.add('${nameOf(p)}: $partial');
if (ownDb.contains(p)) {
final s = l?.importSourceOpenStrapBackup ?? 'OpenStrap backup';
if (!sources.contains(s)) sources.add(s);
Expand Down
95 changes: 95 additions & 0 deletions test/backup/partial_restore_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openstrap_edge/data/backup_extras.dart';
import 'package:openstrap_edge/data/db.dart';
import 'package:openstrap_edge/state/app_state.dart';

import 'backup_support.dart';

void main() {
late BackupEnv env;
setUpAll(() async => env = await BackupEnv.create('bkx_partial_test.db'));
tearDownAll(() async => env.dispose());
setUp(() => FlutterSecureStorage.setMockInitialValues({}));
tearDown(() => LocalDb.debugBeforePageCommit = null);

Future<String> backup() async {
await env.wipe();
await env.seedData();
final db = await LocalDb.instance;
await db.insert('baselines', {
'key': 'movement_floor', 'payload_json': '{}', 'updated_at': 1,
});
final path = await LocalDb.exportCopy();
await env.wipe();
return path;
}

Future<List<int>> rowCounts() async {
final db = await LocalDb.instance;
return [
for (final t in ['decoded_onehz', 'day_result', 'baselines'])
(await db.rawQuery('SELECT COUNT(*) AS n FROM $t '
"WHERE ${t == 'baselines' ? "key = 'movement_floor'" : '1'}"))
.single['n'] as int,
];
}

test('a throw after the day_result page reports what already landed',
() async {
final path = await backup();
final progress = RestoreProgress();
LocalDb.debugBeforePageCommit = (_) async {
if (progress.phase == 'baselines') throw StateError('boom');
};
await expectLater(
LocalDb.importFromDbFile(path, progress: progress), throwsStateError);
expect(progress.committed, isTrue);
expect(progress.phase, 'baselines');
expect(progress.days, 1);
expect(progress.counts['decoded_onehz'], 30);
expect(progress.rows, greaterThanOrEqualTo(31));
expect(await rowCounts(), [30, 1, 0]);

// a retry converges on the clean result, no duplicates
LocalDb.debugBeforePageCommit = null;
await LocalDb.importFromDbFile(path);
expect(await rowCounts(), [30, 1, 1]);
});

test('a throw on the very first page commits nothing', () async {
final path = await backup();
final progress = RestoreProgress();
LocalDb.debugBeforePageCommit = (_) async => throw StateError('boom');
await expectLater(
LocalDb.importFromDbFile(path, progress: progress), throwsStateError);
expect(progress.committed, isFalse);
expect(await rowCounts(), [0, 0, 0]);
});

test('importEdgeBackup says how far it got instead of failing outright',
() async {
final path = await backup();
var pages = 0;
LocalDb.debugBeforePageCommit = (_) async => pages++;
await LocalDb.importFromDbFile(path); // learn the page count
await env.wipe();
final total = pages;
pages = 0;
LocalDb.debugBeforePageCommit =
(_) async => ++pages == total ? throw StateError('boom') : null;
final app = AppState.forTesting();
addTearDown(app.dispose);
final days = await app.importEdgeBackup(path);
expect(days, 1);
expect(app.lastImportPartial,
startsWith('restored 1 days ('));
expect(app.lastImportPartial, contains('rows in finished tables), then stopped: '));
expect(app.lastImportPartial, contains('boom'));

LocalDb.debugBeforePageCommit = null;
await app.importEdgeBackup(path);
expect(app.lastImportPartial, isNull);
expect(await rowCounts(), [30, 1, 1]);
});
}
Loading