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
8 changes: 8 additions & 0 deletions lib/compute/derivation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import '../ble/adapters/signals.dart';
import '../data/coverage_resolver.dart';
import '../data/db.dart';
import '../data/day_label.dart';
import '../data/storage_operation.dart';
import '../data/series_codec.dart';
import '../notify/fired_keys.dart';
import '../notify/notification_center.dart';
Expand Down Expand Up @@ -3759,6 +3760,13 @@ class DerivationEngine {
required Future<int?> Function() freeDiskBytes,
void Function(CompactStep step)? onStep,
bool Function()? busy,
}) => withStorageOperation(() => _compactStorage(
freeDiskBytes: freeDiskBytes, onStep: onStep, busy: busy));

Future<CompactResult> _compactStorage({
required Future<int?> Function() freeDiskBytes,
void Function(CompactStep step)? onStep,
bool Function()? busy,
}) =>
whileIdle(() async {
final before = await LocalDb.databaseBytesOnDisk();
Expand Down
63 changes: 36 additions & 27 deletions lib/data/auto_backup.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import '../state/prefs.dart';
import '../sync/reset_gate.dart';
import 'backup_storage.dart';
import 'db.dart';
import 'storage_operation.dart';

export 'backup_storage.dart' show BackupFolder, AndroidBackupStorage;

Expand Down Expand Up @@ -323,13 +324,19 @@ Future<BackupStorage> _storage() async {

/// Take a backup now, regardless of schedule, and prune old ones.
///
/// Serialized against every other backup path.
/// Serialized against every other backup path and disk-heavy operation.
Future<BackupOutcome> runBackup({
DateTime? now,
Future<String> Function()? exportSnapshot,
BackupStorage? storage,
}) => _serialize(
() => _runBackup(now: now, exportSnapshot: exportSnapshot, storage: storage),
() => withStorageOperation(
() => _runBackup(
now: now,
exportSnapshot: exportSnapshot,
storage: storage,
),
),
);

Future<BackupOutcome> _runBackup({
Expand Down Expand Up @@ -524,28 +531,30 @@ Future<BackupOutcome> runBackupIfDue({
DateTime? now,
Future<String> Function()? exportSnapshot,
BackupStorage? storage,
}) => _serialize(() async {
final when = now ?? DateTime.now();
// Cadence is read here too, for the same reason as the timestamp: a call
// that waits behind an export would otherwise act on the setting as it was
// when it queued. Someone who switches backup OFF while one is running would
// still get another unencrypted copy of their health data written after
// they disabled it.
if (!backupIsDue(cadence: cadence(), lastRun: lastRun(), now: when)) {
return const BackupOutcome(skipped: true);
}
final failedAt = _lastAutoFailure;
if (failedAt != null &&
!failedAt.isAfter(when) &&
when.difference(failedAt) < kBackupRetryAfterFailure) {
return const BackupOutcome(skipped: true);
}
final outcome = await _runBackup(
now: when,
exportSnapshot: exportSnapshot,
storage: storage,
);
_lastAutoFailure = outcome.succeeded ? null : when;
if (outcome.succeeded) await markRun(when);
return outcome;
});
}) => _serialize(
() => withStorageOperation(() async {
final when = now ?? DateTime.now();
// Cadence is read here too, for the same reason as the timestamp: a call
// that waits behind an export would otherwise act on the setting as it was
// when it queued. Someone who switches backup OFF while one is running would
// still get another unencrypted copy of their health data written after
// they disabled it.
if (!backupIsDue(cadence: cadence(), lastRun: lastRun(), now: when)) {
return const BackupOutcome(skipped: true);
}
final failedAt = _lastAutoFailure;
if (failedAt != null &&
!failedAt.isAfter(when) &&
when.difference(failedAt) < kBackupRetryAfterFailure) {
return const BackupOutcome(skipped: true);
}
final outcome = await _runBackup(
now: when,
exportSnapshot: exportSnapshot,
storage: storage,
);
_lastAutoFailure = outcome.succeeded ? null : when;
if (outcome.succeeded) await markRun(when);
return outcome;
}),
);
28 changes: 25 additions & 3 deletions lib/data/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import '../ble/adapters/signals.dart' show InputSignal;
import '../import/import_container.dart';
import 'coverage_resolver.dart' show CoverageInterval;
import 'day_label.dart';
import 'storage_operation.dart';
import 'json_fallback.dart';
import 'activity_store.dart';
import 'attach_copy.dart';
Expand Down Expand Up @@ -11530,6 +11531,16 @@ class LocalDb {
bool includeSubstrateArchive = true,
bool includePrefs = true,
Directory? into,
}) => withStorageOperation(() => _exportCopy(
includeSubstrateArchive: includeSubstrateArchive,
includePrefs: includePrefs,
into: into,
));

static Future<String> _exportCopy({
bool includeSubstrateArchive = true,
bool includePrefs = true,
Directory? into,
}) async {
final db = await instance;
final tmp = into ?? await getTemporaryDirectory();
Expand Down Expand Up @@ -11628,7 +11639,10 @@ class LocalDb {
/// does not make the checkpoint throw: it returns busy = 1 in its first
/// column and leaves the WAL as it was, so the row is read, and tried once
/// more after a moment.
static Future<bool> vacuumAndCheckpoint() async {
static Future<bool> vacuumAndCheckpoint() =>
withStorageOperation(_vacuumAndCheckpoint);

static Future<bool> _vacuumAndCheckpoint() async {
final db = await instance;
await _resetRedriveResume();
await db.execute('VACUUM');
Expand Down Expand Up @@ -12633,7 +12647,10 @@ 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 {
static Future<ImportSummary> importFromDbFile(String path) =>
withStorageOperation(() => _importFromDbFile(path));

static Future<ImportSummary> _importFromDbFile(String path) async {
if (!await File(path).exists()) {
throw const FileSystemException('Backup file not found');
}
Expand Down Expand Up @@ -17163,7 +17180,12 @@ class LocalDb {
/// sync/ACK path, during a live session, or in the background. That gating is
/// the caller's job — see `AppState._maybeReclaimDiskSpace`, which runs it
/// only on a foreground heavy derive with nothing else in flight.
static Future<int> vacuumIfBloated({int minFreeBytes = 64 << 20}) async {
/// Returns -1 when another storage job is in flight; the caller retries
/// later rather than holding the derive latch while it waits for storage.
static Future<int> vacuumIfBloated({int minFreeBytes = 64 << 20}) =>
tryStorageOperation(-1, () => _vacuumIfBloated(minFreeBytes));

static Future<int> _vacuumIfBloated(int minFreeBytes) async {
final free = await freelistBytes();
if (free < minFreeBytes) return 0;
final db = await instance;
Expand Down
20 changes: 9 additions & 11 deletions lib/data/disk_space.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Free space on the volume that holds the database, from the platform.
// Free space on a volume, from the platform.
//
// Only "Compact database" asks: a VACUUM writes a full second copy of the file
// before it drops the first, so it must not start on a nearly full phone.
// VACUUM and backup extraction both need a second copy on disk, so neither
// should consume the space the rest of the app needs to keep working.

import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
Expand All @@ -13,17 +13,15 @@ const MethodChannel _channel = MethodChannel('openstrap/storage');
@visibleForTesting
Future<int?> Function()? debugFreeDiskBytes;

/// Bytes free for the app on the database's volume, or null when the platform
/// cannot say (no channel, a desktop test, an error). Null is "unknown", and
/// every caller treats unknown as not enough.
Future<int?> freeDiskBytes() async {
/// Bytes free for the app on [path]'s volume (the database's by default), or
/// null when the platform cannot say. Callers must handle unknown capacity.
Future<int?> freeDiskBytes({String? path}) async {
final override = debugFreeDiskBytes;
if (override != null) return override();
try {
final v = await _channel.invokeMethod<Object?>(
'freeBytes',
{'path': await getDatabasesPath()},
);
final v = await _channel.invokeMethod<Object?>('freeBytes', {
'path': path ?? await getDatabasesPath(),
});
return v is num ? v.toInt() : null;
} catch (_) {
return null;
Expand Down
46 changes: 46 additions & 0 deletions lib/data/storage_operation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import 'dart:async';

final _ownerKey = Object();
Future<void> _tail = Future<void>.value();
var _pending = 0;

class _StorageOwner {
bool active = true;
}

bool get _ownsStorage =>
(Zone.current[_ownerKey] as _StorageOwner?)?.active ?? false;

/// Disk-heavy jobs on the main isolate must not budget the same free space.
/// Hold this through extraction, consumption and cleanup, not just the query.
/// Nested helpers may re-enter, but must be awaited, not launched in parallel.
/// Acquire before the derive latch; code already holding that latch must use
/// [tryStorageOperation] instead to avoid waiting on an import that needs it.
/// Other isolates/processes are not reserved against; write failures still
/// need their normal cleanup and storage guidance.
Future<T> withStorageOperation<T>(Future<T> Function() action) {
if (_ownsStorage) return Future<T>.sync(action);
final previous = _tail;
final release = Completer<void>();
_tail = release.future;
_pending++;
return (() async {
await previous;
final owner = _StorageOwner();
try {
return await runZoned(action, zoneValues: {_ownerKey: owner});
} finally {
// A callback outliving its job must not inherit ownership forever.
owner.active = false;
_pending--;
release.complete();
}
})();
}

/// Opportunistic VACUUM already holds the derive latch, so it must defer
/// rather than wait behind a restore that may need the same latch.
Future<T> tryStorageOperation<T>(T busy, Future<T> Function() action) {
if (_pending > 0 && !_ownsStorage) return Future<T>.value(busy);
return withStorageOperation(action);
}
Loading